【问题标题】:What are Shadow Variables in Java? [duplicate]Java中的影子变量是什么? [复制]
【发布时间】:2014-12-05 11:47:06
【问题描述】:

我在读一本书时遇到了 Java 中的影子变量这个术语,但没有关于它的描述。最终这些变量的用途是什么?它们是如何实现的?

【问题讨论】:

  • 在Java中,变量分为三种:局部变量、实例变量和类变量。变量有其作用域。不同种类的变量有不同的作用域。如果存在另一个具有相同名称且范围更近的变量,则该变量将被隐藏。换句话说,按名称引用变量将使用范围内最接近的变量,外部范围内的变量将被隐藏。
  • 可以在这篇文章中看到关于阴影的快速思考:stackoverflow.com/questions/8814153/…

标签: java jakarta-ee


【解决方案1】:

我可能会要求您阅读它而不是提供我自己的描述,例如在这里:http://en.wikipedia.org/wiki/Variable_shadowing。一旦您了解了变量的阴影,我建议您继续阅读有关覆盖/阴影方法和一般可见性的内容,以全面了解这些术语。

实际上,自从在 Java 术语中提出问题以来,这里有一个小例子:

    public class Shadow {

        private int myIntVar = 0;

        public void shadowTheVar(){

            // since it has the same name as above object instance field, it shadows above 
            // field inside this method
            int myIntVar = 5;

            // If we simply refer to 'myIntVar' the one of this method is found 
            // (shadowing a seond one with the same name)
            System.out.println(myIntVar);

            // If we want to refer to the shadowed myIntVar from this class we need to 
            // refer to it like this:
            System.out.println(this.myIntVar);
        }

        public static void main(String[] args){
            new Shadow().shadowTheVar();
        }
    }

【讨论】:

  • 尽量不要使用影子变量。它使代码阅读者感到困惑。
猜你喜欢
  • 2011-04-21
  • 2010-11-08
  • 2015-02-28
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
  • 2015-08-11
  • 1970-01-01
相关资源
最近更新 更多