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();
}
}
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
super(some int) as first line of B's constructorConsider that the constructor of a child class implicitly calls super().
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.
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