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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With