为什么我不能在包外部使用受保护的构造函数来编写这段代码:
package code; public class Example{ protected Example(){} ... }
Check.java
package test; public class Check extends Example { void m1() { Example ex=new Example(); //compilation error } }
编辑:
编译错误:
构造函数Example()不可见
protected修饰符仅用于包中以及包外部的子类中。使用对象创建对象时Example ex=new Example();,默认情况下将调用父类的构造函数。
Example ex=new Example();
由于父类构造函数受到保护,因此您会遇到编译时错误。您需要根据JSL 6.6.2.2调用受保护的构造函数,如示例2所示。
package Super; public class SuperConstructorCall { protected SuperConstructorCall() { } } package Child; import Super.SuperConstructorCall; public class ChildCall extends SuperConstructorCall { public static void main(String[] args) { SuperConstructorCall s = new SuperConstructorCall(); // Compile time error saying SuperConstructorCall() has protected access in SuperConstructorCall } }
符合JLS 6.6.2.2的示例2 :
package Super; public class SuperConstructorCall { protected SuperConstructorCall() { } } package Child; import Super.SuperConstructorCall; public class ChildCall extends SuperConstructorCall { public static void main(String[] args) { SuperConstructorCall s = new SuperConstructorCall(){}; // This will work as the access is by an anonymous class instance creation expression } }