Search code examples
javainheritanceconstructorthissuper

does "this" keyword on subclass constructor requires superclass default constructor to be implicitly defined?


Following code requires superclass constructor need to be implicitly defined for this keyword to work

public class SuperEx {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Child c=new Child(10,"AK");
        c=new Child("Hi","AK");

    }

}
class Parent{
    int n;
    String s;
    Parent(int n, String s){
         this.n=n;
         this.s=s;
        System.out.println("Parent constructor arg value is "+n +" and " +s);
    }
}
class Child extends Parent{

     Child(int i, String n){
         super(i,n);
         System.out.println("child 2nd Constructor");

     }
     Child(String s, String s1){
         this(s,s1,"hello");
     }
/*here im getting error in eclipse IDE which says "Implicit super constructor Parent() is undefined. Must explicitly invoke another constructor*/
     Child(String s, String s1, String s3){
         System.out.println("values are "+s+" "+s1+" "+s3);
     }

}
  1. The above code is typed in eclipse neon ide.

  2. Compilation error is shown in Child constructor with three arguments.

  3. Does this keyword requires SuperClass constructor to be implicitly defined.

Solution

  • The issue is Parent does not have a default constructor. So if someone wants to create an instance of child via Child(String s, String s1, String s3) constructor, how will Parent be instantiated ?

    This has nothing to explicitly do with constructor chaining (this()). The reason you are not getting an error in Child(String s, String s1) is because you are actually invoking super(i,n); via this(s,s1,"hello"); [constructor chaining]

    So you need to describe a way to create the parent class in the last constructor, either by directly calling super in it or transitively via constructor chaining or create a default constructor of Parent.