什么是Java类中使用的变量阴影? [英] What is variable shadowing used for in a Java class?

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

问题描述

我正在阅读我的Deitel,Java How to Program一书,并且遇到了 shadowing 一词。如果允许阴影,在Java类中它有什么情况或用途?

I'm reading my Deitel, Java How to Program book and came across the term shadowing. If shadowing is allowed, what situation or what purpose is there for it in a Java class?

示例:

public class Foo {

    int x = 5;

    public void useField() {
        System.out.println(this.x);
    }
    public void useLocal() {
        int x = 10;
        System.out.println(x);
    }
}


推荐答案

阴影的基本目的是将本地代码与周围的类分离。如果它不可用,请考虑以下情况。

The basic purpose of shadowing is to decouple the local code from the surrounding class. If it wasn't available, then consider the following case.

API中的Class Foo已发布。在您的代码中,您将其子类化,并在子类中使用名为bar的变量。然后Foo发布更新并将一个名为Bar的受保护变量添加到其类中。

A Class Foo in an API is released. In your code you subclass it, and in your subclass use a variable called bar. Then Foo releases an update and adds a protected variable called Bar to its class.

现在,由于您无法预料到的冲突,您的课程将无法运行。

Now your class won't run because of a conflict you could not anticipate.

但是,不要故意这样做。只有在你真的不关心范围之外发生的事情时才会发生这种情况。

However, don't do this on purpose. Only let this happen when you really don't care about what is happening outside the scope.

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

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