gpt4 book ai didi

java - 为什么我不能在包外使用 protected 构造函数?

转载 作者:IT老高 更新时间:2023-10-28 20:23:31 25 4
gpt4 key购买 nike

为什么我不能为这段代码在包外使用 protected 构造函数:

package code;
public class Example{
protected Example(){}
...
}

检查.java

package test;
public class Check extends Example {
void m1() {
Example ex=new Example(); //compilation error
}
}
  1. 为什么即使我已经扩展了类(class),我也会收到错误消息?请解释

编辑:

编译错误:

The constructor Example() is not visible

最佳答案

通常 protected 意味着只能被同一包中的子类或类访问。然而,这里是来自 JLS 的构造函数的规则:

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.

例如,这不会编译

public class Example extends Exception {

void method() {
Exception e = new Exception("Hello", null, false, false);
}
}

但这确实

public class Example extends Exception {

Example() {
super("Hello", null, false, false);
}
}

这也是

public class Example {

void method() {
Exception e = new Exception("Hello", null, false, false) {};
}
}

所以规则是明确的,但我不能说我理解它们背后的原因!

关于java - 为什么我不能在包外使用 protected 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29530199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com