java - 使用 protected 构造函数实例化一个类

标签 java protected access-modifiers

public class MyTest {
    public static void main(String str[]){
        Info i=new Info();
        i.value=20;
        System.out.println("Integer value is :"+i.value);
    }
}
class Info {
    int value;
    protected Info(){
    System.out.println("Class with protected constructor");
    }
}

-->我遗漏了一些有关 protected 修饰符的内容,但无法弄清楚。 --> 直到现在我已经读到一个带有 protected 构造函数的类只能由它的子类实例化,而且在同一个包或不同的包中也是如此。那上面怎么给我这个输出:Class with protected constructor 整数值为:20

最佳答案

因为 MyTestInfo 这两个类都在同一个包中。

同一个包中的类可以毫无问题地访问 protected 成员

If the member or constructor is declared protected, then access is permitted only when one of the following is true:

  • Access to the member or constructor occurs from within the package containing the class in which the protected member or constructor is
    declared.

检查 JLS 6.6.2

关于java - 使用 protected 构造函数实例化一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22450772/

相关文章:

java - 如何使用 Commons FileUpload 设置用于存储文件上传的文件夹

java - Hibernate - 解析映射文件(.hbm.xml)时出现问题

java - 了解 Java 的 protected 修饰符

scala - 从 Scala 调用 Java : protected constructor

java - 访问修饰符

c# - C# 中 "internal"关键字的实际用途

java - KafkaConsumer Java API subscribe() 与 assign()

java - 旋转移动 Sprite

Java:接口(interface)之前的 protected 方法

java - 为什么 Java 中不允许较弱的重写函数?