To make it compile to you need to call super(int)
instead of calling super()
implicitly.
Pony(int age) {
super(age);
this.age = age;
}
Then you may notice that both Horse
and Pony
have exactly the same field which holds exactly the same data. Why would Pony
need to have the field age
if the class Pony
is based on (Horse
) already defined this field?
Pony(int age) {
super(age);
}
It's the beauty of inheritance: you may make use of anything that was already written in the base class.
However, the compiler complains that the parent class has no default constructor.
It complains because, as I mentioned above, it failed to invoke super()
.
If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.
https://docs.oracle.com/javase/specs/jls/se12/html/jls-8.html#jls-8.8.7
What if I want the parent and child class to only have constructors with parameters?
Then the child class should always explicitly state what parent's constructor it wants to call.
Am I right to conclude that a parent class always needs a default or no-arg constructor?
No, it's fine to have a parent class without the default constructor as long as its children don't invoke super()
.