4

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?

Eran
  • 387,369
  • 54
  • 702
  • 768
Shipra Sharma
  • 421
  • 4
  • 10
  • Because object needs to create all parent objects. class `Super` needs a parameter to create its instance, so you have to pass the argument this way to `Super`'s constructor – maskacovnik Dec 20 '15 at 15:59
  • Mainly, because that's just how Java is defined. It will insert a call to `super()` for you, but it *won't* insert a call to `super(argsHere)` for you. It's just inconsistent in that way. Many other languages require that their equivalents to the `super()` call be explicit, too, which maintains consistency. Java just doesn't. Every language has quirks. *(Not dissing Java.)* – T.J. Crowder Dec 20 '15 at 16:05

2 Answers2

7

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

because a 'Super' object needs to be created in order to create a 'Sub' object. and if you don't have any empty (default) c'tor you have to use one of the existing ones.

Victor Bouhnik
  • 198
  • 2
  • 14