【发布时间】:2015-12-15 14:57:29
【问题描述】:
我对编程还很陌生,不明白为什么这段代码会打印 200 而不是 206。Cat 类中的 move 方法覆盖 Animals 类中的 move 方法。为什么第 2 行方法调用后 Animals 中的 'location' 实例变量没有变为 206?但是,当我删除类 Cat 中的方法时,实例变量 DOES 变为 206。这背后的逻辑是什么?
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;
}
}
【问题讨论】:
-
你使用调试功能了吗?试一试......然后你会看到你的执行到底是哪条路径。
-
从类
Cat中删除int location = 400。
标签: java inheritance polymorphism pass-by-value