Thursday 4 February 2016

this() and super() constructor calls in java

this() and super() constructor calls in java:
=================================

this() and super() are constructor calls.
We can use this() and super() constructor calls only inside the constructor,if we are using other than constructor we are going to get compile time error.
this():
-------
this() constructor call is used to refer current class constructor

super():
---------
super() constructor call is used refer immediate parent class constructor from the child class.

Example on this() and super() constructor calls:
----------------------------------------------------------------

package blog;

class Test1
{
int a;
String str;

Test1(int a,String str)
{
this();//calling current class default constructor
this.a=a;
this.str=str;
}

Test1()
{
System.out.println("default constructor");
}
}

class Test2 extends Test1
{

      int a,c;
      String str;
      Test2(int a,String str,int c)
      {
   super();//calling super class constructor
   this.a=a;
   this.str=str;
   this.c=c;

     }

}

public class ThisSuperDemo {

public static void main(String[] args) {

Test1 test1 =  new Test1(80,"selenium");
Test2 test2 = new Test2(10,"Ramesh Selenium",90);
System.out.println(test2.a);
System.out.println(test2.c);
System.out.println(test2.str);
}


}




1 comment: