使用受保护的构造函数对类进行匿名初始化 [英] Anonymous initialization of class with protected constructor

查看:190
本文介绍了使用受保护的构造函数对类进行匿名初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一堂课:

public class SomeClass {    
    protected SomeClass () { 
    }
}

在位于不同包中的MainClass中,我尝试执行两行:

In MainClass located in different package I tried to execute two lines:

public static void main(String[] args) {
    SomeClass sac1 = new SomeClass(); 
    SomeClass sac2 = new SomeClass() {}; 
}

由于protected构造函数,在两种情况下我都期望程序失败.令我惊讶的是,匿名初始化工作得很好.有人可以解释一下为什么第二种初始化方法还可以吗?

Because of protected constructor, in both cases I was expecting program to fail. To my suprise, anonymous initialization worked fine. Could somebody explain me why second method of initialization is ok?

推荐答案

您的匿名课程

SomeClass sac2 = new SomeClass() {}; 

基本上变成

public class Anonymous extends SomeClass {
    Anonymous () {
        super();
    }
}

构造函数没有访问修饰符,因此您可以在同一包中毫无问题地调用它.您还可以调用super(),因为可以从子类构造函数访问protected父构造函数.

The constructor has no access modifier, so you can invoke it without problem from within the same package. You can also invoke super() because the protected parent constructor is accessible from a subclass constructor.

这篇关于使用受保护的构造函数对类进行匿名初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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