Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java subclass prints parameter default values instead of assigned values

I am doing some reading and practice to better understand java inheritance. When I run the Lion class below, it prints out 0 and null. I think it should rather print out the parameters values i.e. 30 and roars. what I am doing wrong?

public class Animal {

    int numTeeth;

    public Animal(int numTeeth) {
        numTeeth = this.numTeeth;
    }

    public int getNumTeeth() {
        return numTeeth;
    }   
    public void setNumTeeth(int numTeeth) {
        this.numTeeth = numTeeth;       
    }
}


public class Lion extends Animal {

    String sound;

    public Lion(int numTeeth, String sound) 
    {
        super(numTeeth);
        sound = this.sound;
    }

    public String getSound() {          
        return sound;
    }

    public void setSound(String sound) {        
        this.sound = sound;
    }

    public static void main(String[] args) {

        Lion simba = new Lion(30, "roars");     
        System.out.println(simba.getNumTeeth());
        System.out.println(simba.getSound());
    }
}
like image 345
Nobi Avatar asked May 25 '26 09:05

Nobi


1 Answers

Your field assignments are the wrong way around, it should be

this.numTeeth = numTeeth;

and

this.sound = sound;

Otherwise you assign the field to the local variable, which does not make much sense.

like image 51
luk2302 Avatar answered May 26 '26 22:05

luk2302



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!