受保护的构造函数和可访问性 [英] Protected constructor and accessibility

查看:296
本文介绍了受保护的构造函数和可访问性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们不能使用受保护的构造函数来实例化一个类,如果它的子类在不同的包中?如果可以访问受保护的变量和方法,为什么不适用于受保护的构造函数?

Why can't we instantiate a class with a protected constructor if its child is in a different package? If protected variables and methods can be accessed, why doesn't the same rule also apply for a protected constructor?

pack1:

package pack1;

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

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

pack2:

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。合格访问 protected 构造函数



C 其中声明了 protected 构造函数的类,并且 S 是其声明中使用 protected 构造函数。然后:

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:


  • 如果访问是通过超类构造函数调用 super(...) code>或限定超类构造函数调用 E.super(...),其中 E

如果访问是通过匿名类实例创建表达式 new C(...){...} 或一个合格的匿名类实例创建表达式 E.new C(...){...} ,其中 E 是主要表达式,则允许访问。

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.

如果访问是通过一个简单的类实例创建表达式 new C(...)表达式 E.new C(...),其中 E ,或者方法引用表达式 C :: new ,其中 C ClassType 可以通过类实例创建表达式(不声明匿名类)或方法引用表达式访问 protected 构造函数

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.

在您的情况下,从 B的构造函数中访问 A B / code>通过调用 super()。但是,使用的访问不合法。

In your case, access to the protected constructor of A from B would be legal from a constructor of B through an invocation of super(). However, access using new is not legal.

这篇关于受保护的构造函数和可访问性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆