Java 中的影子变量是什么? [英] What are Shadow Variables in Java?

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

问题描述

我在读一本书时遇到了 Java 中的影子变量一词,但没有对其进行描述.最终这些变量的用途是什么?它们是如何实现的?

I was reading a book and came across the term Shadow Variables in Java but there was no description for it. Eventually what are these variables used for and how are they implemented?

推荐答案

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

Instead of providing my own description i may ask you to read about it for example here: http://en.wikipedia.org/wiki/Variable_shadowing. Once you understood the shadowing of variables i recommend you proceed reading about overlaying/ shadowed methods and visibility in general to get a full understanding of such terms.

实际上,由于这个问题是在 Java 方面提出的,这里是一个小例子:

Actually since the question was asked in Terms of Java here is a mini-example:

    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();
        }
    }

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

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