Thursday, 24 April 2014

Single Level Inheritance

One class derived from other class. It is also called as simple Inheritance.


Class B derived from class A. I.e, B is the sub class and A is the super class.

   Class A{

   }

   class B extends A{

   }

Whenever sub class constructor is called, the super class default constructor called internally by default.

Example
class A{

   A(){
      System.out.println("I am class A's default constructor");
   }
 
   A(int a){
      System.out.println("I am class A's parameterized constructor");
   }

}

class B extends A{

   B(){
      System.out.println("I am class B's default constructor");
   }
 
   B(int a){
      System.out.println("I am class B's parameterized constructor");
   }
 
   public static void main(String args[]){
      B obj1 = new B();
      B obj2 = new B(10);
   }

}

Output
I am class A's default constructor
I am class B's default constructor
I am class A's default constructor
I am class B's parameterized constructor

As you observe the output
1. Super class constructor called first before executing the subclass constructor code.

2. Super class default constructor is called in the sub class constructors by default.

That's fine, but I want to call the super class parameterized constructor. How can I call that ?

For that there is a keyword called super, used to call super class constructor, to access super class variables and methods.
class B extends A{

   B(){
      System.out.println("I am class B's default constructor");
   }
 
   B(int a){
      super(a);
      System.out.println("I am class B's parameterized constructor";
   }
 
   public static void main(String args[]){
      B obj1 = new B();
      B obj2 = new B(10);
   }

}

Output
I am class A's default constructor
I am class B's default constructor
I am class A's parameterized constructor
I am class B's parameterized constructor

As you observe the above output, subclass parameterized constructor called the super class parameterized constructor explicitly, so the default constructor is not called.

Some points to Remember
1. Can I use super and this in one constructor ?
No, call to super or this must be first statement in constructor. So you can use either super or this but not both.


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment