简体   繁体   English

公共班级的私人内部阶级的可见性

[英]Visibility of a private inner class of a public class

While this is obviously a RTFM case, somehow I failed to find a concise source explaining it all. 虽然这显然是RTFM案例,但我不知何故找不到简明的资料来解释这一切。

public class Outer {

   private class Inner {

   }

}

Private class Inner is an inner class of a public class Outer . 私有Inner是一个inner类中的公共Outer

My question is about visibility of Inner from outside `Outer'. 我的问题是关于“外部”外部“ Inner ”的可见性

  1. Should I be able to instantiate Inner in another class? 我应该能够在另一个课程中实例化Inner吗? If yes, are there any limitations (like this class being in the same package, etc.)? 如果是,是否有任何限制(例如,此类位于同一包中,等等)?

  2. Can Inner be used as a concrete type when using collections? 使用集合时,可以将Inner用作具体类型吗? For example, should I be able to declare ArrayList <Inner> in another class? 例如,是否可以在另一个类中声明ArrayList <Inner>

  3. If another class extends Outer will Inner come along in terms of the above questions? 如果另一个班级extends Outer Inner 是否遇到上述问题?

内部是私有的,因此只有其父外部可以使用它做任何事情。

The "FM" in this case is the Java Language Specification. 在这种情况下,“ FM”是Java语言规范。 You want section 6.6.1 which includes: 您需要第6.6.1节 ,其中包括:

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. 否则,如果将成员或构造函数声明为私有,则仅当访问发生在包含成员或构造函数的声明的顶级类(第7.6节)的主体内时,才允许访问。

So the constructor can be called anywhere within the declaration of Outer (including within any other nested classes that Outer declares), but nowhere else. 因此,可以在Outer声明内的任何地方(包括在Outer声明的任何其他嵌套类中)调用构造函数,而在其他地方则不能调用。 Access is not inherited - it's as simple as whether the source code that's trying to call the constructor is within the source code of Outer . 访问权限不是继承的-就像试图调用构造函数的源代码是否在Outer的源代码内一样简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM