3

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;
    }
}
Helenesh
  • 3,999
  • 2
  • 21
  • 36

3 Answers3

8
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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
3

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.

alampada
  • 2,329
  • 1
  • 23
  • 18
2

enforce your print out to say that your object is actually a Cat:

    System.out.println(((Cat)a).location); //it prints 406

the best way to approach this problem is to use Java properly, you shouldn't call the variable directly, rather you should call the method.

here is a better approach to get what you want:

public  class Animals {
    int location = 200; //line 1

   public void move(int by) {
      location = location+by;
   }

   public int getLocation(){
    return location;
   }

    public final static void main (String...args) {
        Animals a = new Cat();
        a.move(6); //line 2
        System.out.println((a).getLocation()); //note we are now calling a getter method not the variable itself
    }
}

class Cat extends Animals {
    int location = 400;


   public int getLocation(){
    return location;
   }


    public void move(int by){
       location = location+by;
    }
}
nafas
  • 5,283
  • 3
  • 29
  • 57