0

The instance of class Singleton will be instantiated when the method getInstance() was called. I wonder why i can instantiate outer class from the static inner class?

public class Singleton{
   private Singleton(){}

   private static class SingletonHolder{
      private static Singleton INSTANCE = new Singleton();
   }

   public static Singleton getInstance(){
      return SingletonHolder.INSTANCE;
   }
}
  • 5
    Because `private` means in this class only, and the inner class is **in** the outer class. โ€“ Elliott Frisch Mar 11 '20 at 15:11
  • 1
    Does this answer your question? [Why can outer Java classes access inner class private members?](https://stackoverflow.com/questions/1801718/why-can-outer-java-classes-access-inner-class-private-members) โ€“ beatrice Mar 11 '20 at 15:15
  • (In this *outer* class. There are weird edge cases, but they're edge cases if you're doing something dirty. I forget what they are.) Also, I can make an instance of that "singleton" (a antipattern). The single holder antipattern is almost always counter productive - classes are loaded lazily, you're just adding more work and more confusion. And, most importantly, just say no to global state. โ€“ Tom Hawtin - tackline Mar 11 '20 at 15:21

1 Answers1

1

From JLS 6.6.1

Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level type (ยง7.6) that encloses the declaration of the member or constructor.

Your access occurs within the body of the top-level type that encloses the private constructor declaration, so access is permitted.


So, whilst what you have is allowed, this would not be:

public class Singleton{
   private Singleton(){}
   // ..
}

// Second top-level class in same file.
class Foo {
  Singleton s = new Singleton();
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243