Java中的可变阴影 [英] Variable shadowing in Java

查看:148
本文介绍了Java中的可变阴影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此Java代码有些疑问.它给出的输出是"furry bray".我的问题:

I am having some doubts about this Java code. The output it gives is "furry bray". My questions:

  1. 为什么我得到这个输出?
  2. 如何访问String对象引用名称"?在ZooKeeper类中?
  3. 如果它与变量屏蔽有关,那么哪个变量正在被屏蔽?

代码:

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?
   }
 }

推荐答案

变量不是多态的.当您访问m.name时,它将始终使用Mammal.name字段作为对象的一部分,而与对象的执行时间类型无关.如果需要访问Zebra.name,则需要一个编译时类型为Zebra的表达式.

Variables aren't polymorphic. When you access m.name, that will always use the Mammal.name field which is part of that object, regardless of the execution-time type of the object. If you need to get access to Zebra.name, you need an expression with a compile-time type of Zebra.

虽然实际上调用了makeNoise方法-执行时使用的实现确实是 ,具体取决于对象的类型.

The makeNoise method is called virtually though - the implementation used at execution time does depend on the type of the object.

请注意,如果您将所有字段都设为私有-无论如何这通常是个好主意-这最终不会成为问题.

Note that if you make all your fields private - which is generally a good idea anyway - this doesn't end up being an issue.

这实际上是隐藏而不是阴影.有关隐藏的详细信息,请参见 JLS 8.3 . 第6.4.1节进行阴影处理.我不能说我总是保持分歧...

This is actually hiding rather than shadowing. See JLS section 8.3 for details on hiding, and section 6.4.1 for shadowing. I can't say that I always keep the differences straight...

这篇关于Java中的可变阴影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆