私有成员访问 Java [英] Private Member Access Java

查看:44
本文介绍了私有成员访问 Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是类级别还是对象级别的私有成员访问.如果是对象级别的,那么下面的代码应该不会编译

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();
   }
}

请说明在 sub 的 messWithI() 方法中访问 obj 的成员 i 是否有效

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

推荐答案

正如 DevSolar 所说,它处于(顶级)类级别.

As DevSolar has said, it's at the (top level) class level.

来自 Java 语言规范的第 6.6 节:

否则,如果会员或构造函数被声明为私有,然后允许访问当且仅当它发生在顶部的主体内包含以下内容的级别类(第 7.6 节)成员的声明或构造函数.

Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

请注意,没有迹象表明它仅限于特定对象的成员.

Note that there's no indication that it's restricted to members for a particular object.

从 Java 7 开始,编译器不再允许访问类型变量的私有成员.因此,如果该方法具有类似 public <T extends PrivateMember> 的签名,void messWithI(T t) 那么访问 t.i 将是一个编译器错误.但是,这不会改变您的特定场景.

As of Java 7, the compiler no longer allows access to private members of type variables. So if the method had a signature like public <T extends PrivateMember> void messWithI(T t) then it would be a compiler error to access t.i. That wouldn't change your particular scenario, however.

这篇关于私有成员访问 Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆