Java 类中的变量遮蔽有何用途?
我正在阅读 Deitel 《Java How to Program》一书,并偶然发现了术语“影子”。 如果允许隐藏,那么在 Java 类中存在什么情况或目的?
例子:
public class Foo {
int x = 5;
public void useField() {
System.out.println(this.x);
}
public void useLocal() {
int x = 10;
System.out.println(x);
}
}
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?
Example:
public class Foo {
int x = 5;
public void useField() {
System.out.println(this.x);
}
public void useLocal() {
int x = 10;
System.out.println(x);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
阴影的基本目的是将本地代码与周围的类解耦。 如果不可用,请考虑以下情况。
API 中的 Foo 类被发布。 在您的代码中,您对其进行子类化,并在您的子类中使用名为 bar 的变量。 然后 Foo 发布了更新,并向其类添加了一个名为 Bar 的受保护变量。
现在,由于您无法预料的冲突,您的课程将无法运行。
但是,不要故意这样做。 只有当你真的不关心范围之外发生的事情时才允许这种情况发生。
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.
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.
它对于您不想为方法参数创建单独的变量名的设置器很有用,例如:
除此之外,我会避免使用它们。
It can be useful for setters where you don't want to have to create a separate variable name just for the method parameter eg:
Apart from that I'd avoid them.
一个主要目的是迷惑人们。 这是不好的做法,应该避免。
One major purpose is to confuse people. It's bad practice and should be avoided.
Shadowing 并不是 Java 特有的术语。 在任何情况下,如果某个作用域中声明的变量与更大作用域中的变量同名,则该变量会被隐藏。
阴影的一些常见用途是当您有内部类和外部类并且想要维护具有相同名称的变量时。
如果你可以避免它,你应该这样做,因为它可能会引起混乱。
Shadowing is not really a java only term. In any instance where a variable declared in a scope has the same name as one in a bigger scope, that variable is shadowed.
Some common uses for shadowing is when you have inner and outer classes and want to maintain a variable with the same name.
If you can avoid it though, you should since it may cause confusion.
两个常见的用途是构造函数和设置方法:
如果您想要在单个时刻获得变量的副本,但在方法调用中变量可能会发生变化,那么偶尔它会很有用。
(当然,一个人为的例子对于豪华的 for 循环来说是不必要的。)
The two common uses are constructors and set methods:
Very occassionally it's useful if you want a copy of the variable at a single instant, but the variable may change within the method call.
(Of course, a contrived example made unnecessary with the posh for loop.)