Private Member Access Java

2019-01-14 09:40发布

Is the private member access at the class level or at the object level. If it is at the object level, then the following code should not compile

    class PrivateMember {
   private int i;
   public PrivateMember() {
      i = 2;
   }
   public void printI() {
      System.out.println("i is: "+i);
   }
   public void messWithI(PrivateMember t) {
      t.i *= 2;
   }
   public static void main (String args[]) {
      PrivateMember sub = new PrivateMember();
      PrivateMember obj = new PrivateMember();
      obj.printI();
      sub.messWithI(obj);
      obj.printI();
   }
}

Please clarify if accessing the member i of obj within the messWithI() method of sub is valid

7条回答
干净又极端
2楼-- · 2019-01-14 10:27

The same page says, in sub-section 6.6.8, you can also find the following statement:

A private class member or constructor is accessible only within the body of the top level class that encloses the declaration of the member or constructor. It is not inherited by subclasses.

The private class member whose access we evaluate here is i.

public void messWithI() is a method that exists within the body of the top level class where i has been declared, which is, precisely, PrivateMember.

Your construct meets the statement above, and that is why it runs without problems.

Thas is another way to say the same as Jon and Devsolar.

Access modifiers for class members are related to where the code is written, (in which package, and in which class), regardless of what kind of member the access gets granted: a class member or an instance member.

Logically, you cannot use an instance member of a class if you do not have an instance of the class, but that is a different issue, related to the life-cycle of the member.

查看更多
登录 后发表回答