本文介绍了私有成员访问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.

来自:

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 08:04
查看更多