Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 545
Shipra Sharma Avatar asked Jan 07 '23 23:01

Shipra Sharma


1 Answers

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.

like image 97
Eran Avatar answered Jan 15 '23 00:01

Eran