Does a parent class always need a default or no-argument constructor even if the child class already has a defined constructor?

K Man :

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?

JB Nizet :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=124686&siteId=1
Recommended