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

查看:349
本文介绍了什么是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天全站免登陆