访问 Java 中受保护的构造函数

Access to a protected constructor in Java

如果我有一个 class A 及其子class B.

package washington;
public class A{
       protected A(){}
}

package washington;
public class B extends A{
      public B(){super();} // it works
      public static void main (String[] args){
      A b = new A(); // it does work.
       }
}

classA有一个受保护的构造函数,但是我不能访问B中的构造函数。我认为这是一个规则,但是我找不到描述这种情况的网页..我看到的都提到了protected 可以从 subclass 访问,同包.... e.t.c.

package california;
public class A extends washington.A{
    public static void main (String[] args){
       new washington.A(); // it does not work.
    }
}

不知道是不是因为我用的是IntelliJ IDEA 2017.3.4..编译器是javac 9.0.4

看来问题是您的 类 在不同的包中。 Java doc 说:

If the access is by a simple class instance creation expression new C(...), or a qualified class instance creation expression E.new C(...), where E is a Primary expression, or a method reference expression C :: new, where C is a ClassType, then the access is not permitted. A protected constructor can be accessed by a class instance creation expression (that does not declare an anonymous class) or a method reference expression only from within the package in which it is defined.

class A{
    protected A() {
        System.out.println("hello from A");
    }
}

class B extends A{
    public B() {
        super();
        System.out.println("hello from B");
    }

    public static void main (String[] args){
        A b1 = new B(); // you can either do this
        B b2 = new B(); // or this
    }
}

尝试 运行 该程序,您将在控制台上看到预期的结果。