Search code examples
javaconstructoraccess-modifiers

Private construtor in inner class initialized within outer class


Is it possible to initialize an instance of an inner class which has a constructor marked as private from within the outer class. I was under the impression that once a constructor was declared private no one can create an instance of the class except from within the class itself. Example

Public class Outerclass 
    {
        newinstance = new Innerclass();

       private final class InnerClass 
       {
         private InnerClass(//paremeters)
         {
            //constructor declaration inside
          } 
       }
    }

Solution

  • Inner classes are members of their outer class so they have full access to all the other members, and all the other members have full access to them.

    The access markers in an inner class apply only to unrelated classes. And since your inner class is private in itself, it is only accessible for construction from its outer class.