Java 私有(private)构造函数可见性

标签 java constructor private

在谈到构造函数时,我试图理解为什么类成员的可访问性之间存在差异。

考虑以下示例:

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/

相关文章:

java - org.hibernate.PropertyNotFoundException : Could not find a getter for id in class model. 联系人

java - 我的构造函数没有接受变量

exception-handling - Ninject - 如何在构造过程中识别哪个类抛出异常

actionscript-3 - 访问 protected 或私有(private)属性(property)

c++ - 限制对类方法的访问

java - 使用 ArrayList 的迭代器时出现 ArrayIndexOutOfBoundsException

java - 如果 Android API 级别低于 26,如何将存储访问框架与 MediaMuxer 一起使用

java - 为什么要在类中声明变量私有(private)?

Java 扫描仪从第二次开始工作

c++ - 构造函数内部 "this"的 dynamic_cast