Reputation: 1109
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());
}
}
Upvotes: 3
Views: 65
Reputation: 4569
When you're assigning numTeeth
or sound
- compiler sees the most close local variable with the same name. When you specify this.sound
- it means you want to access the field of current object.
So, when you're doing numTeeth = this.numTeeth
- you're assigning the value of your field to the local variable. You have to swap it - this.numTeeth = numTeeth
- so, you're assigning the value of the local variable(parameter) to the field.
Also, to avoid such mistakes, you can use Hungarian notation or underline the field names:
class Test {
int mCount;
//or
int _count;
Test(int count) {
_count = count;
mCount = count;
}
}
Upvotes: 0
Reputation: 45309
This code:
public Scratch(int numTeeth) {
numTeeth = this.numTeeth;
}
Is doing the opposite of what you intend it to do (overwriting the parameter with the default value in the instance field). It should be:
public Scratch(int numTeeth) {
this.numTeeth = numTeeth;
}
When local variables reuse an an instance field's name, qualify the instance variable name with this
or class name if it's static.
To help yourself prevent this in future, you could make your input parameters final, which will simply cause your original code not to compile.
public Scratch(final int numTeeth) {
this.numTeeth = numTeeth;
}
The same applies to the sound variable too.
Upvotes: 3
Reputation: 57114
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.
Upvotes: 4