为什么我不能在包外使用受保护的构造函数? [英] Why can't I use protected constructors outside the package?

查看:213
本文介绍了为什么我不能在包外使用受保护的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能在包外面使用受保护的构造函数来获取这段代码:

Why can't I use protected constructors outside the package for this piece of code:

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

Check.java

Check.java

package test;
public class Check extends Example {
  void m1() {
     Example ex=new Example(); //compilation error
  }
}




  1. 为什么即使我延长了课程,我也会得到错误?
    请解释

编辑:

编译错误:


构造函数Example()不可见

The constructor Example() is not visible


推荐答案

protected modifier仅用于包中和包外的子类。当您使用示例ex = new Example(); 创建对象时,默认情况下它将调用父类构造函数。

protected modifier is used only with in the package and in sub-classes outside the package. When you create a object using Example ex=new Example(); it will call parent class constructor by default.

作为受保护的父类构造函数,您将收到编译时错误。您需要根据JSL 6.6.2.2调用受保护的构造函数,如下面的示例2所示。

As parent class constructor being protected you are getting a compile time error. You need to call the protected constructor according to JSL 6.6.2.2 as shown below in example 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
    }
}

示例2符合 JLS 6.6.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 
    }
}

这篇关于为什么我不能在包外使用受保护的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆