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

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

问题描述

我正在阅读我的 Deitel, Java How to Program 一书,遇到了阴影这个词.如果允许阴影,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);
    }
}

推荐答案

shadowing 的基本目的是将本地代码与周围的类解耦.如果它不可用,请考虑以下情况.

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 中的 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天全站免登陆