I'm fairly new to programming and do not understand why this code prints 200 instead of 206. The move method in class Cat overrides the move method in class Animals. Why does the 'location' instance variable in Animals not change to 206 after the method call on line 2? However, when I remove the method in class Cat, then the instance variable DOES change to 206. What is the logic behind it?
public class Animals {
int location = 200; //line 1
public void move(int by) {
location = location+by;
}
public final static void main (String...args) {
Animals a = new Cat();
a.move(6); //line 2
System.out.println(a.location); //200, but should print 206 in my opinion
}
}
class Cat extends Animals {
int location = 400;
@Override
public void move(int by) { //if this method is removed, a.location prints 206
location = location+by;
}
}
a.move(6); // line 2
System.out.println(a.location);
In first line you are executing the method in Cat, which means you are modifying the variable of Cat class.
In second line you are printing the variable from Animal.
You cannot override variables in Java. Only methods.
And what you did is you shadowed the instance variable location on Cat and when you modify that in your Cat class, you are not pointing to Animal no more. When you remove that variable in Cat class, then you are referring to Animal Class.
The problem is that you define location in both the super class and the subclass. Therefore, there are two different variables. Cat.move modifies Cat.location. However, if you use a base class reference to get location you get the animal's instance location instead of cat's location.
One way to fix it is to mark location protected in Animal and initialise its value (200 or 400) in the default constructor of each class.
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