Java 类中使用的变量阴影是什么?

编程入门 行业动态 更新时间:2024-10-11 17:30:18
本文介绍了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 类中使用的变量阴影是什么?

本文发布于:2023-11-27 22:38:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639886.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   类中   阴影   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!