Why can\'t this()
and super()
both be used together in a constructor?
What is the reason for incorporating such a thing?
Because if you use this()
and super()
together in a constructor it will give compile time error. Because this()
and super()
must be the first executable statement. If you write this()
first than super()
will become the second statement and vice-versa. That's why we can't use this()
and super()
together.
And there is a condition in both that they have to be declared in the first line of the constructor you are using. And that's the reason why we can't use both in a single constructor because you can write only one thing in your first line.
this() and super(), both are the constructors that's why must be the first statement. But we can use both in a program.
this(): It is used to call, same class Default or Parametrized Constructor.
super(): It is used to call, immediate super/parent class Default or Parametrized Constructor.
//Super Class
public class SuperConstructor {
SuperConstructor(){
this(10);
System.out.println("Super DC");
}
SuperConstructor(int a){
this(10,20);
System.out.println("Suer SPC with Iteger");
}
SuperConstructor(int i,int j){
System.out.println("Super with DPC with Iteger and Integer");
}
}
//subclass
public class ThisConstructor extends SuperConstructor{
ThisConstructor(){
this(10,20);
System.out.println("Subcalss DC ");//DC Default Constructor
}
ThisConstructor(int i){
super(i);
System.out.println("Subcalss SPC with Iteger");//SPC Single Parameterized Constructor
}
ThisConstructor(int i, String s){
this();
System.out.println("Subcalss DPC with Iteger and String");//DPC double Parameterized Constructor
}
ThisConstructor(int i,int age){
super(i,age);
System.out.println("Subcalss DPC with Iteger and Integer");
}
public static void main(String []k){
System.out.println("=================Frist time Calling ==========================\n");
ThisConstructor t = new ThisConstructor(1);
System.out.println("=================Second time Calling ==========================\n");
ThisConstructor t1 = new ThisConstructor(1,2);
}
}