【发布时间】:2013-06-05 13:26:01
【问题描述】:
我对这段 Java 代码有些怀疑。它给出的输出是“毛茸茸的布雷”。我的问题:
- 为什么我会得到这个输出?
- 如何在 ZooKeeper 类中访问字符串对象引用“name”?
- 如果它与变量阴影有关,那么阴影是哪个变量?
代码:
class Mammal {
String name = "furry ";
String makeNoise() { return "generic noise"; }
}
class Zebra extends Mammal {
String name = "stripes ";
String makeNoise() { return "bray"; }
}
public class ZooKeeper {
public static void main(String[] args) { new ZooKeeper().go(); }
void go() {
Mammal m = new Zebra();
System.out.println(m.name + m.makeNoise());
//Output comes as "furry bray". Please explain this.
//And how can we access the name variable, the one having "stripes " in it.
//Does it have something to do with Variable Shadowing?
}
}
【问题讨论】:
-
当子类和父类都有同名的变量时,子类的变量隐藏了父类的变量,所以当我们试图通过持有子类的对象来访问父类引用的变量时,它将从父类,阅读我的博客programmingmitra.com/2018/02/…
标签: java