Pages

Thursday, May 7, 2020

Inheritance in Java


In this, we will cover below topics:

1) What is Inheritance
2) How to achieve Inheritance?
3) Types of inheritance
4) Constructor
5) this
6) super


1. What is Inheritance:

1. Inheritance is inheriting features of from parent class to child class is called as Inheritance.
2. In java it can be achieved by using extends keyword.
3.  It is used to achieve Polymorphism.
4. types of inheritance: Simple, Multilevel, Hierarchical, multiple, etc.

Realtime Example:

Let’s CONSIDER below example which will clear the concept of inheritance:
How features transfers using Inheritance



Example -II
New version of android contains all the features of old version i.e all features of Old version of android  inherited to New version of android.
let's see above example in programming language.

Another example of Inheritance


2. How to achieve Inheritance?


public class A {  //A is Super class

     int a = 10;
     int b = 20;

     public void m1() {
          System.out.println("In m1 of class A");
     }
}


public class B extends A {  //B is Sub class

     int c = 30;
    
     public static void main(String[] args) {

          B obj = new B();
         
          /*Accessing all element of Super class A via object of Sub class B */
         
          System.out.println(obj.a);
          System.out.println(obj.b);
          System.out.println(obj.c);

          obj.m1();
     }
}


So from above basic program we can conclude that B gets/inherits all the features from Super class A.
Variable a, b and method  m1 from class A inherited to B (via extends keyword)


Use of Inheritance/ Why to use inheritance in Java:

1. To Re-usability of code.

2. To achieve Polymorphism.

3. If some code in project is required repeatedly or need to use many places/classes, so we can make one class Let’s say Base class and write all repeatedly required code in that class so that we can avail all the features by just extending that Base class.


3. Types of inheritance:



1. Simple Inheritance: (Class B extends A):
Simple Inheritance

2. Multilevel Inheritance: (Class C extends B and Class B extends class A):
Multilevel Inheritance
3.  Hierarchical Inheritance : (Class B and C extends A)
Hierarchical Inheritance


4. Multiple Inheritance: (Class A extending both class B and C)


Multiple Inheritance


Note: In Java, Multiple inheritance is NOT possible due to ambiguity. If we write code as Class C extends A,B then it will give compile time error.


To understand Inheritance, we should aware of internal flow/communication between classes. We should also know about following 3 concepts to communicate between classes:
1. Constructor
2. this
3. super


4. What is Constructor?


1. It is same as that of class name but does not have any return type.
JVM (Java Virtual Machine) puts constructor by default as below after compile :

          class A {                                         class A{
                           After compile ---->>           A() {   }
                     }                                                   }

             A.java                                              A.class

2.  It can overload but cant override (Example is given).

3. If we give any return type to constructor then it will not give any error, that will act as normal method:
class A {
   int A () {

             }
     }
4. Recursion between constructor is allowed (See program).

5. They are called as a time of object creation.

6. constructor can have any modifier : public, default, private, protected.

7. constructor can Not be final, abstract or static.

8. By making constructor as Private we can stop other to create an object. Private constructor can be used in a “Singleton design pattern”. (See section of Singleton design pattern)

9. It is used to create class object, initialization of class, calling constructors of super & current class using super() & this() respectively.

10. There are 5 ways (may be more) to call Constructor. Constructor calls are as below:-
  • A a1 = new A();
  • new A();
  • this();
  • super();
  • Class.forName.newInstance();


5. What is this and this()


1. “this” is keyword and “this()” is constructor calls

2. this is used to call current class members(methods & variables) and “this()”  is call to call current class constructor.

3. It represent the current class object.

4. Recursion using this is not allowed in Java.

5. this()  must be 1st line of constructor to call constructor of current class (usually used to call parameterized constructor )

6. if this() called from method then it may gives compile time error.

7. Lets see below program of this/this():


package thisexample;

public class A {

     int a = 10;
     int b = 20;

     // default constructor
     A() {
          System.out.println("Value of A: " + this.a); // 3. print a=10
          System.out.println("Value of B: " + this.b);// 4. print b=20
          this.m1();// 5. Execute m1()
          this.m2("Parameterized method invoked"); // 6. Execute m2()
     }

     // Parameterized constructor
     A(int c) {
          this(); // 2. default constructor called i.e ThisEx()
          System.out.println("--------------------------"); // 7. Print this and below 2 lines
          System.out.println("Parameterized constructor called..!");
          System.out.println("Value of C: " + c);
     }

     public void m1() {
          System.out.println("m1 is called..!");
     }

     public void m2(String str) {
          System.out.println("m2: " + str);
     }

     public static void main(String[] args) {
          new A(3); // Step 1: here Parameterized constructor called..!
     }
}

Output:

Value of A: 10
Value of B: 20
m1 is called..!
m2: Parameterized method invoked
--------------------------
Parameterized constructor called..!
Value of C: 3




6. What is super and super()


1. Like super/super () is also working as same as of this/this(). Difference is only that this is used to call current class constructor and super is used to call super class constructor.

2. “super” is keyword and “super()” is constructor call for super class Not for current class

3. super is used to call super class members(methods & variables) and “super()”  is call to call super class constructor.

4. super() represent the super class object.

5. super()  must be 1st line of constructor to call constructor of super class.

6. if super() called from method then it may gives compile time error.

7. Lets see below program to understand super/super():


public class A { // A is Super class

     int a = 10;
     int b = 20;

     A() { // step 3: find A()
          System.out.println("Default superclass Contrustor!"); // step 4: print
     }

     A(int a1) {// step 9 : find A(int a1)
          System.out.println("Parametrized superclass Contrustor!"); // step 10: Print
     }

     public void m1() { // step 12 : find method
          System.out.println("In m1 of class A"); // step 13: execute m1()
     }
}


public class B extends A { // B is Sub class

     B() { // 2
          super();// 3: go to A()
          System.out.println("a= "+super.a); // step 4
          System.out.println("b= "+super.b); // step 5
     }

     B(int x) { // step 7: find B(int x)
          super(3); // step 8: go to super i.e A(int a1)
          super.m1();// step 11: call m1 in A class
     }

     public static void main(String[] args) {

          B obj1 = new B(); // Step 1: call B()
          B obj2 = new B(3); // step 6: call B(int x)
     }
}


Output:

Default superclass Contrustor!
a= 10
b= 20
Parametrized superclass Contrustor!
In m1 of class A




NOTE: All interview questions and maximum programs on this topic will be covered in another section. 


4 comments:

  1. All challenging questions and programs will be posted soon

    ReplyDelete
  2. Plse post some design pattern interview questions and collections most interview point questions

    ReplyDelete
    Replies
    1. Yeah sure, will upload that as well.

      Please find below link for interview questions:
      https://corejavasea.blogspot.com/2020/05/top-20-java-interview-programs.html

      Delete

**** Please let me know if you have any doubts. ****