Why can\'t this() and super() both be used together in a constructor?
What is the reason for incorporating such a thing?
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);
}
}