java - protected 构造函数和可访问性

标签 java constructor

如果子类在不同的包中,为什么我们不能用 protected 构造函数实例化一个类?如果可以访问 protected 变量和方法,为什么同样的规则不适用于 protected 构造函数?

包装1:

package pack1;

public class A {
    private int a;
    protected int b;
    public int c;

    protected A() {    
        a = 10;
        b = 20;
        c = 30;
    }
}

包装2:

package pack2;

import pack1.A;

class B extends A {
    public void test() {
        A obj = new A(); // gives compilation error; why?
        //System.out.println("print private not possible :" + a);
        System.out.println("print protected possible :" + b);
        System.out.println("print public possible :" + c);
    }
}

class C {
    public static void main(String args[]) {
        A a = new A(); // gives compilation error; why?
        B b = new B();
        b.test();
    }
}

最佳答案

根据 Java 规范 (https://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls-6.6.2.2)

6.6.2.2. Qualified Access to a protected Constructor

Let C be the class in which a protected constructor is declared and let S be the innermost class in whose declaration the use of the protected constructor occurs. Then:

  • If the access is by a superclass constructor invocation super(...), or a qualified superclass constructor invocation E.super(...), where E is a Primary expression, then the access is permitted.

  • If the access is by an anonymous class instance creation expression new C(...){...}, or a qualified anonymous class instance creation expression E.new C(...){...}, where E is a Primary expression, then the access is permitted.

  • 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.

在您的情况下,访问 A 的 protected 构造函数来自 B对于 B 的构造函数是合法的通过调用 super() .但是,使用 new 访问不合法。

关于java - protected 构造函数和可访问性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5150748/

相关文章:

javascript - MurmurHash3_32 Java 返回负数

java - Struts2 让拦截器不为某些类运行

java - Spring AspectJ 风格 AOP

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

constructor - Prolog 中的多个构造函数

c++ - 如何在 C++ 中使用条件初始化对象正确获取资源?

java - Java中构造函数的参数有什么要求吗

java - 如何在Android键盘中设置关闭选项

java - java中非静态方法如何访问静态成员?

java - 为什么不在 java 的匿名类中构造函数?它与 OOPs 规则相矛盾