Java - Class method can see private fields of same-class parameter

柔情痞子 提交于 2019-12-01 20:29:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!