Reputation: 465
I'm new to Java and I see that we cannot subclass a class that has its constructor as private
. However, I came across this code which creates a subclass whose super class' constructor is private.
In short:
This works:
class A {
static class B {
private B() {
out.println("Constructor of B");
}
}
static class C extends B {
C() {
out.println("Constructor of C");
}
}
}
While this doesn't:
class B {
private B() {
out.println("Constructor of B");
}
}
class C extends B {
C() {
out.println("Constructor of C"); // No default constructor available for super class
}
}
Can anyone please help me understand what's going on here?
Upvotes: 4
Views: 140
Reputation: 1500065
There's a subtlety about private
that you may not have grokked yet. From JLS 6.6:
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.
So forgetting about inheritance for the moment, that means that all the code within a top-level type, including the code within nested types, has access to all the private members declared within the same top-level type, including members declared within nested types.
Here's an example of that:
public class TopLevel {
private static void foo() {
}
static class Nested1 {
private static void bar() {
}
}
static class Nested2 {
private static void callFooBarFromNested() {
foo();
Nested1.bar();
}
}
private static void callFooBarFromTopLevel() {
foo();
Nested1.bar();
}
}
From there, it's only a small step to see why your first example is fine - the parameterless constructor in C
needs to chain to the parameterless constructor in B
, which it can do when they're both nested in the same top-level class, but not otherwise.
Upvotes: 5