我是 Java 新手,我发现我们不能将其构造函数设为 private
的类进行子类化。然而,我遇到了这个code它创建一个子类,其父类(super class)的构造函数是私有(private)的。
简而言之:
这有效:
class A {
static class B {
private B() {
out.println("Constructor of B");
}
}
static class C extends B {
C() {
out.println("Constructor of C");
}
}
}
虽然这不是:
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
}
}
谁能帮我理解这里发生了什么?
最佳答案
private
有一个微妙之处,您可能还没有领悟到。来自 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.
所以暂时忘记继承,这意味着顶级类型中的所有代码(包括嵌套类型中的代码)都可以访问同一顶级类型中声明的所有私有(private)成员,包括声明的成员在嵌套类型中。
这是一个例子:
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();
}
}
从那里,只需一小步即可了解为什么您的第一个示例很好 - C
中的无参数构造函数需要链接到 B
中的无参数构造函数,这当它们都嵌套在同一个顶级类中时可以这样做,但其他情况则不然。
关于java - Java静态内部类的私有(private)构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59883074/