I cannot get this code to compile.
class Horse {
private int age;
Horse(int age) {
this.age = age;
}
}
class Pony extends Horse {
private int age;
Pony(int age) { //here compiler complains about no default constructor in parent class
this.age = age;
}
}
I know you must define a constructor for a child class when the parent class only has constructors with parameters, and that is what I have done. However, the compiler complains that the parent class has no default constructor.
Am I right to conclude that a parent class always needs a default or no-arg constructor? What if I want the parent and child class to only have constructors with parameters?
Am I right to conclude that a parent class always needs a default or no-arg constructor?
No. The first thing a subclass constructor must do is to invoke one of the superclass constructors. If you don't, then the compiler calls the no-arg constructor of the superclass for you. But of course that fails if the superclass doesn't have one.
Your code should be:
class Pony extends Horse {
Pony(int age) {
super(age);
}
}
See, the superclass already has an age field, and probably methods that use that field. So redeclaring one in the subclass is wrong and counter-productive.