简体   繁体   中英

Why can a private inner class with a private constructor be sub-classed?

class ClassA
{    
    private ClassA() 
    {
    }        
}

class ClassB extends ClassA
{
    //here we will get a compiler error that cannot extend a class with private constructor
}

public class GenericTestClass 
{        
    private class TestingInnerPrivateClass
    {    
         private TestingInnerPrivateClass() 
         {
         }

        public void display()
        {
            System.out.print("Test");
        };       
    }

    public class InnerPublicClass extends TestingInnerPrivateClass
    {
        //here i am able to extend a private class
    }

    public static void main(String[] args)
    {
        GenericTestClass genericTestClass = new GenericTestClass();
        GenericTestClass.InnerPublicClass innerPublicClassInstance = genericTestClass.new InnerPublicClass();
        innerPublicClassInstance.display();
    }
}

If you look at the code above, you can see that I am not able to extend classB from classA , but I am able to extend InnerPublicClass from InnerPrivateClass .

I am not able to understand how a class which is private and has a private constructor as well is able to be sub-classed when it is an inner class.

InnerPublicClass is defined inside GenericTestClass , and therefore has access to all the private members of this class, which includes the inner class TestingInnerPrivateClass . Therefore it can extend TestingInnerPrivateClass .

And here's a relevant quote from JLS 6.6.1 :

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.

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