Java-类方法可以看到相同类参数的私有字段 [英] Java - Class method can see private fields of same-class parameter
问题描述
我遇到了一个很奇怪的行为,不确定是Java问题还是Eclipse的问题.
I'm encountering a rather odd behavior, and not sure if this is a Java issue or just something with Eclipse.
采用以下代码:
class Foo {
private String text;
public void doStuff(Foo f) {
System.out.println(f.text);
}
}
这里的问题是,为什么f.text可以访问?这是一个私有字段,按照我的逻辑,它不应该是,但IDE似乎认为是.
The problem here is, why is f.text accessible? It's a private field, so by my logic, it shouldn't be, but the IDE seems to think it is.
推荐答案
这是设计使然.在相同的类中,即使在不同的实例中,也可以访问私有字段.请参阅此处,以获取更多详细信息以及Oracle对此的正式声明. .由于doStuff
是Foo
的成员,因此可以访问Foo
的任何私有字段.
This is by design. Private fields are accessible within the same class, even if a different instance. See here for more details and an official statement from Oracle on this. Since doStuff
is a member of Foo
, any private fields of Foo
are accessible for it.
private修饰符指定只能在其自己的类 [甚至从其他实例]中访问该成员. [强调我的]
The private modifier specifies that the member can only be accessed in its own class [even from a different instance]. [emphasis mine]
现在,由于text
的可见性修饰符,以下代码示例不起作用:
Now, the following code example does not work due to text
's visibility modifier:
class Bar{
public int baz;
public void doMoreStuff(Foo f){
System.out.println(f.text);
}
}
因为doMoreStuff是在Bar
中定义的,而不是在Foo
中定义的.
since doMoreStuff is defined in Bar
, not Foo
.
这篇关于Java-类方法可以看到相同类参数的私有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!