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

查看:184
本文介绍了私有成员访问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();
   }
}

请说明是否访问了obj中的成员i subWithI()方法是有效的

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开始,编译器不再允许访问类型变量的私有成员。因此,如果该方法具有类似的签名,则公共< 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天全站免登陆