外部类可以访问内部类的成员吗?
内部类是在类内部定义的类,内部类可以声明为public、private、protected。如果内部类定义为private和protected,外部类可以访问内部类的成员吗?内部类可以访问外部类的成员吗?
The inner class is the class defined inside a class, and the inner class can be declared as public, private, protected. If the inner class defined as private and protected, can outer class access the members of inner class? and can inner class access members of outer class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的。这些限定符只会影响内部类在从外部类派生的类中的可见性。
是的,包括那些声明为
private
的方法,就像任何实例方法一样。Yes. These qualifiers will only affect the visibility of the inner class in classes that derive from the outer class.
Yes, including the ones declared
private
, just as any instance method can.一般来说,您可以(访问内部类上的私有字段,反之亦然)。下面的代码在 Eclipse 下编译:
也就是说,您可以配置 IDE/编译器将对此类字段的访问视为错误(在 Eclipse 中,此设置称为“访问封闭类型的不可访问成员”,位于 Preferences -> 下) Java -> 编译器 -> 错误/警告 -> 代码样式
In general, you can (access private fields on inner classes and vice-versa). The following code compiles under Eclipse:
That said, you can configure your IDE/compiler to treat accesses to such fields as errors (in Eclipse this setting is called "Access to non-accessible member of an enclosing type", under Preferences -> Java -> Compiler -> Error/Warnings -> Code Style)
解释是在常规内部类的上下文中[常规内部类不能在其中声明静态成员]
您可以从内部类直接访问外部类的任何字段。
即使外部类也可以访问内部类的任何字段,但可以通过内部类的对象来访问。
Explanation is in context of regular inner class[Regular inner classes cannot have static members declared inside them]
You can access any field of outer class from inner class directly.
Even Outer class can access any field of Inner class but through object of inner class.
一书。)
至于你的问题:你自己测试一下很容易。但答案是肯定的(即使对于
private
成员),只要您不尝试从静态上下文访问非静态成员(除了引用),或者尝试访问位于不可访问范围内的成员即可 。会期望=)。
(Joshua Bloch, from the book Effective Java.)
As for your questions: it is very easy to test by yourself. But the answer is yes (even for
private
members), as long as you are not trying to access a non-static member (other than from a reference) from a static context, or trying to access a member which is in an inaccessible scope.That is, very much as one would expect =).
是的!您可以从外部类访问内部类成员,反之亦然(无论访问修饰符如何)。
但是,对于静态嵌套类,您不能仅通过字段名称访问其字段,而需要像
直接通过字段名称从内部类访问外部类的静态字段一样访问它。
Yes! You can access both an inner class member from outer class, and vice-versa(irrespective of the access modifier).
However, for a static nested class you cannot access its field just by the field name, and you need to access it like
though you can access the static fields of the outer class from the inner class directly by the fields names.