Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); 
    } 
}
like image 392
George Irimiciuc Avatar asked Dec 01 '22 02:12

George Irimiciuc


2 Answers

Your class A uses an explicit argument-taking constructor, so the default no-args constructor is not present implicitly.

For your class B to successfully extend A you either need:

  • A no-args explicit constructor declared in A
  • Or a call to super(some int) as first line of B's constructor

Consider that the constructor of a child class implicitly calls super().

like image 58
Mena Avatar answered Dec 04 '22 13:12

Mena


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.

like image 39
Jon Skeet Avatar answered Dec 04 '22 13:12

Jon Skeet