Why can a separate inner class with a private constructor be subclassed?
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 cannot expand classB
from classA
, but I can expand InnerPublicClass
from InnerPrivateClass
.
I cannot figure out how a class that is private and has a private constructor can also be subclassed when it is an inner class.
source to share
InnerPublicClass
is defined internally GenericTestClass
and therefore has access to all private members of that class, which includes the inner class TestingInnerPrivateClass
. Therefore, it can expand TestingInnerPrivateClass
.
And here is the relevant quote from JLS 6.6.1 :
if a member or constructor is declared private, then access is allowed if and only if it occurs within the body of a top-level class (ยง7.6) that includes a member or constructor declaration.
source to share