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());
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With