0

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?

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
  • 1
    You cannot create the instance outside, you may have a reference if the class in question inherits from a top level class, then you can use an object of an inner class, but still cannot even cast it. The idea is use it internally in your own class. If you return the array I'm not sure what would be the behavior, let's try it. – porfiriopartida Sep 27 '13 at 22:01
  • remove the () from your inner class declaration. – porfiriopartida Sep 27 '13 at 22:03

2 Answers2

5

Inner is private, therefore only its parent, Outer, can do anything at all with it.

Adam Miller
  • 767
  • 1
  • 9
  • 22
2

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194