在谈到构造函数时,我试图理解为什么类成员的可访问性之间存在差异。
考虑以下示例:
class A {
static class B {
private B(String s) {}
private void foo() {}
}
static class C extends B {
public C(String s) {
super(s); // call B(String), which is private, and obviously accessible
}
void bar() {
foo(); // compilation error (symbol unknown), as B.foo() is private
}
}
}
A
的私有(private)成员,由于是私有(private)的,不应从 B
访问。对于字段和方法,确实如此,但构造函数似乎没有遵循相同的规则。
从 JLS-8 ( 6.6.1. Determining Accessibility ),我们可以读到:
[...]
A member (class, interface, field, or method) of a reference type, or a constructor of a class type, is accessible only if the type is accessible and the member or constructor is declared to permit access:
[...]
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 class (§7.6) that encloses the declaration of the member or constructor.
谁能解释一下为什么构造函数可以从 C
访问,即使被声明为 private
?
最佳答案
foo()
方法是私有(private)的,所以不能继承,也不能直接从C
类调用。
但是,您可以从 B
看到私有(private)方法和构造函数,因为所有内容都在同一个包含类中声明,并使用 super
访问它们,这就是 的原因super()
有效。
同理,你可以使用 super.foo()
来访问 foo
。
注意你可以在C
中重新定义一个新的foo方法,但是这个方法不会覆盖B.foo()
。
关于Java 私有(private)构造函数可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33800344/