我对此Java代码有一些疑问。它给出的输出是“毛茸茸的布雷”。我的问题:
- 为什么我会得到这个输出?
- 如何访问 ZooKeeper 类中的字符串对象引用“名称”?
- 如果它与变量阴影有关,那么哪个变量被阴影?
代码:
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?
}
}