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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With