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
最佳答案
因为 MyTest
和 Info
这两个类都在同一个包中。
同一个包中的类可以毫无问题地访问 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/