bruce
bruce

Reputation: 78

do all the subclass's constructors with parameters needs super(args) when superclass only have one constructor with parameters?

class Animal{
    String s;
    Animal(String s){
        this.s = s;     
    }   
}


class Dog extends Animal{
    Animal animal;
    Dog(String s) {
        super(s);       
    }
    //here is an error "Implicit super constructor Animal() is undefined.Must explicitly invoke another constructor"
    Dog(Animal animal){
        this.animal = animal;       
    }   
}

my confuse is, I've already called the superclass's constructor-with-parameters in

Dog(String s) {
    super(s);       
}

but why I still get the error message in another constructor Dog(Animal animal)?

How the constructor mechanism works in this example?

Thanks!

Upvotes: 3

Views: 66

Answers (2)

GhostCat
GhostCat

Reputation: 140427

And the answer to your question is simply: yes.

Any subclass constructor must first make a call to super. If the superclass has only one ctor taking some arguments, then those "super calls" in your sub classes have to use that ctor.

Upvotes: 5

Scary Wombat
Scary Wombat

Reputation: 44814

Your code is incorrect. As Dog extends Animal then Dog does not need (and should not have) a Animal Object

The correct way is

class Animal{
    String s;
    Animal(String s){
        this.s = s;     
    }  

    // add a setter and getter
    public String getS () {return s;}
    public void setS (String s) {this.s = s;} 
}


class Dog extends Animal{
    Dog(String s) {
        super(s);       
    }
}

Upvotes: 4

Related Questions