简体   繁体   中英

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.

public class Outer {

   private class Inner {

   }

}

Private class Inner is an inner class of a public class Outer .

My question is about visibility of Inner from outside `Outer'.

  1. Should I be able to instantiate Inner in another class? 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? For example, should I be able to declare ArrayList <Inner> in another class?

  3. If another class extends Outer will Inner come along in terms of the above questions?

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

The "FM" in this case is the Java Language Specification. You want section 6.6.1 which includes:

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.

So the constructor can be called anywhere within the declaration of Outer (including within any other nested classes that Outer declares), but nowhere else. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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