为什么我可以访问封闭类引用的私有成员 [英] Why can I access the private members of an enclosing class reference

查看:152
本文介绍了为什么我可以访问封闭类引用的私有成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到很多关于访问封闭类的私有成员的问题。但是,我的问题恰恰相反。

I have seen many questions about accessing private members of an enclosing class. However, my question is the opposite.

如果我有(作为例子),则代码如下:

If I have (as an example), the following code:

public class A {

   private String outerString = "silly string";

   static class B {
      private final A someA = new A();      

      public void foo() {
         String b = someA.outerString ;
      }
   }
}

我想知道为什么会这样编译?我希望通过我从类A(通过someA.outerString)访问'outerString'实例变量的方式来预测错误。我知道内部类可以通过隐式的this引用直接访问封闭的类成员。但是在这里,B类是静态的,所以'this'引用不适用。

I'm wondering why this compiles? I would have expected an error by virtue of the way in which I am accessing the 'outerString' instance variable from class A (via someA.outerString). I know that an inner class can access the enclosing class members directly by an implicit 'this' reference. But here, class B is static, so the 'this' reference won't apply.

推荐答案

B A的成员因此可以访问 A 私有字段和方法。

在这种情况下,虽然 B static 但它正在使用A的实例访问字段 A.outerString

B is a member of A and therefore has access to A's private fields and methods.
In this case, although B is static it is using an instance of A to access the field A.outerString.

这篇关于为什么我可以访问封闭类引用的私有成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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