Java – pass by value and polymorphism
•
Java
See English answers > why Java polymers not work in my example
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; } }
Solution
a.move(6); // line 2
a.move(6); // line 2 System.out.println(a.location);
In the first line, you are executing the method in cat, which means that you are modifying the variables of cat class
On the second line, you will print variables from animal
You cannot override variables in Java There is only one way
What you do is you hide the instance variable position on cat. When you modify it in cat class, you no longer point to animal When you delete this variable in the cat class, you mean animal class
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码