问题
I'm encountering a rather odd behavior, and not sure if this is a Java issue or just something with Eclipse.
Take the following code:
class Foo {
private String text;
public void doStuff(Foo f) {
System.out.println(f.text);
}
}
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.
回答1:
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.
The private modifier specifies that the member can only be accessed in its own class [even from a different instance]. [emphasis mine]
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);
}
}
since doMoreStuff is defined in Bar
, not Foo
.
来源:https://stackoverflow.com/questions/17384322/java-class-method-can-see-private-fields-of-same-class-parameter