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

天涯浪子 提交于 2019-12-01 19:25:06

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.

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