Search code examples
javaconstructorsubclasssuperclass

Why is it mandatory to call a Super class's parameterized constructor inside subclass's parameterized constructor in java?


The code below fails to compile:

class Super
{ 
    int i = 0;    
    Super(String text)
    {
        i = 1; 
    } 
} 

class Sub extends Super
{
    Sub(String text)
    {
       ------------LINE 14------------
        i = 2; 
    }     
    public static void main(String args[])
    {
        Sub sub = new Sub("Hello"); 
        System.out.println(sub.i); 
    } 
}

But when I'm adding super(text) at line 14, it's working fine. Why is it so?


Solution

  • A constructor that doesn't have an explicit call to a super class constructor will be added an implicit call to the parameterless constructor (as if the super(); statement was added a its first statement).

    In your case, since the super class has a constructor with parameters, it has no parameterless constructor, so super(); can't pass compilation, and you must call super(text) explicitly.