您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

为什么我不能在包外使用受保护的构造函数?[重复]

为什么我不能在包外使用受保护的构造函数?[重复]

protected修饰符仅用于包中以及包外部的子类中。使用对象创建对象时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 
    }
}
其他 2022/1/1 18:29:01 有608人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶