Why can't I create a parameterless subclass constructor when the baseclass has a constructor with a parameter?

I know the following doesn't work, but can you help me understand why?

class A {
    A(int x) { 
       System.out.println("apel constructor A"); 
    } 
}

class B extends A {
    B() { 
       System.out.println("apel constructor B"); 
    } 
}

public class C {
    public static void main(String args[]) { 
       B b = new B(); 
    } 
}
Jon Skeet
people
quotationmark

Every constructor (other than in Object) must chain to another constructor as the very first thing it does. That's either using this(...) or super(...).

If you don't specify anything, the constructor implicitly adds super() to chain to a parameterless constructor in the superclass. Sooner or later, you need to go through a constructor for every level of the inheritance hierarchy. This ensures that the state of the object is valid from every perspective, basically.

In your case, you don't have a parameterless constructor in A, hence why B fails to compile. To fix this, you'd either need to add a parameterless constructor to A, or explicitly chain to the parameterised A constructor in B:

public B() {
    super(0); // Or whatever value you want to provide
}

See JLS section 8.8.7 for more details.

people

See more on this question at Stackoverflow