Inheritance in Java with example

Inheritance is a concept in java where new classes can be produced from existing classes. The newly created class acquires all the features of existing class from where it is derived.
         
          Inheritance can be implemented in java using two keywords:
          1.  extends              2. implements

          Producing new class from existing classes is called inheritance.
             •     The newly produced class is called sub class. The original class is called super class.
             •     Extends is the keyword use in inheritance.

Syntax:

1
class SubClass extends SuperClass

             •   Reusability is the main advantage of inheritance
             •   Because of reusability developing of software/program becomes easy.
             •  Sub class contains a copy of super class
             •  In inheritance, we create object to only sub class. Because in sub class it contains all the methods & objects of a class are available to sub class.

Case 1: If super class has default constructor

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.javatbrains.oops;

class One{
     One(){
          System.out.println("Inside One class");
     }
}

class Two extends One{
     Two(){
          System.out.println("Inside Two class");
     }
}

public class ConstDemo {

     public static void main(String[] args) {
          new Two();
     }

}
OutPut:
     Inside One class
     Inside Two class

              •  When you create an object to sub class to super class constructor is also available to sub class.
              •   Super class default constructor also available to sub class.
              •   Super class parametrised constructor is not available in subclass.

Case 2: If super class has parametrised constructor

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.javatbrains.oops;

class One1 {
     int i;

     One1(int i) {
          this.i = i;
     }

     void show() {
          System.out.println("Super class method = " + i);
     }
}

class Two2 extends One1 {
     int i;

     Two2(int x, int y) {
          super(x);  //Calling Super class default constructor
          i = y;
     }

     void show() {
          System.out.println("Sub class method = " + i);
          System.out.println(super.i);
          super.show(); //Calling Super class show method
     }

}

public class ParamConstDemo {

     public static void main(String[] args) {
          Two2 t = new Two2(100, 200);
          t.show();
     }

}
OutPut:
     Sub class method = 200
     100
     Super class method = 100

               •  Super keyword refers to super class from sub class
               •   Using super keyword we can refer to super class instance variables constructors, methods also.
               •  Super.show() in sub class. It shows super class method.
               •  We have to initialize first super class constructor.

Types of Inheritance:
Single Inheritance: Producing sub classes from super class is called single inheritance.

Multiple Inheritance: Producing sub classes from multiple super classes is called multiple inheritance.

               •  Multiple inheritance does not support in java.

Why multiple inheritance is not available in Java?
          Multiple inheritance leads to confusion for programmer. This is against to the aim of java be a simple programming language.
          Java = C++ -Complexity
          There is no operator loading in java. There is no destructor in java. Destructor work is done by Garbage collector.

How can you call garbage collector?
          By calling System.gc(); It will runs the garbage collector. Runtime and system classes of java.lang package System.gc() is available.

Can you create object for System class?
          No, it is not possible. System class can not be instantiated because it contains static methods. finalize() method belongs to class of java.lang package. finalize() method destroys the memory. If you call the finalize() it may crash the program, so it is better to avoid calling finalize() method.
         
          finalize() method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because java has only finite number of these resources and you do not know when the garbage collection is going to Kick in to release these non-memory resources through the finalize() method.

          Garbage collector will work automatically; we should not required to call it.

        1. Multiple inheritance can be achieved by programmers by using interfaces.

1
2
3
class Z extends A,B (Invalid)

class Z implements A,B (Valid)

          A class can implement more than one interface.

        2. Multiple inheritance can be achieved by repeated use of single inheritance.
Hybrid inheritance in the above image first line represents the multiple inheritance and last line represents the single inheritance. So, this is the combination of multiple and single inheritance.

Ex: Multiple inheritance example with interface

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.javatbrains.oops;

interface Father{
     //variables are by default public static final
     int prop1 = 500000;
     float ht1 = 6.0f;
}

interface Mother{
     int prop2 = 900000;
     float ht2 = 5.6f;
}

class Child implements Father,Mother{
    
     void property(){
          System.out.println("Child property is = "+(prop1+prop2));
     }
     void height(){
          System.out.println("Child height is = "+(ht1+ht2)/2);
     }
}

public class Multi {

     public static void main(String[] args) {
          Child ch = new Child();
          ch.property();
          ch.height();
     }
}

OutPut:
     Child property is = 1400000
     Child height is = 5.8

Encapsulation, IS-A, HAS-A:
           •   Encapsulation helps hide implementation behind an interface.
           •   Encapsulated code has two features
           •   Instance variables are kept protected(usually with the private modifier)
           •   Getter and Setter methods provide access to instance variables.
           •    IS-A refers to inheritance or implementation
           •    IS-A is expressed with the keyword extends
           •    IS-A, "inherits from" and "is a subtype of" are all equivalent expressions.
           •    HAS-A means an instance of one class "has a" reference to an instance of another class or another instance of the same class.

Inheritance:
           •   Inheritance allows a class to be a subclass of a super class, and thereby inherit public class protected variables and methods of the super class.
           •  Inheritance is a key concept that underlies IS-A, polymorphism, overriding, overloading and casting.
           •   All classes (except class Object), are subclasses of type Object, and therefore they inherit Objects methods.

Comments

Popular posts from this blog

Hibernate auto increment with example

how to count the page views by using JSP

Multithreading in java with example

How to retrieve data from table by using JDBC with example

Prime, Fibonacci and Factorial number with example in java

How to insert images into database using JDBC?

How to sort list of objects in java with examples

String interview questions and answers

Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException

Store file into table by using JDBC with example