类中的私有构造函数用法 [英] private constructor usage in class

查看:160
本文介绍了类中的私有构造函数用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有私有构造函数,JVM是否会插入对超级构造函数的调用?

If there is a private constructor, does the JVM insert a call to the super constructor?

我指的是私有构造函数中的 super()调用。

I'm referring to the super() call in that private constructor.

class Alpha {
    static String s="";
    protected Alpha(){
        s+="alpha";
    }
}

class SubAlpha extends Alpha{
    private SubAlpha(){
        s+="sub";
    }
}

class SubSubAlpha extends Alpha{
    private SubSubAlpha(){
        s+="subsubAlpha";
    }

    public static void main(String[] args){
        new SubSubAlpha();
        System.out.print(s);   
    }
}

这里我没有收到任何编译错误。这里的 SubSubAlpha 类中有私有构造函数。该编译器是否插入 super()调用,如果是这样,那么 SubAlpha 类中会发生什么。即使有私人建设者。如果没有访问,继承树如何继续到顶部。

Here I don't get any compilation error. Here in the SubSubAlpha class there is private constructor. Is that compiler insert super() call in that if so, what happens in the SubAlpha class. Even there is private constructor. And if that is not accessed how the inheritance tree continues till the top.

推荐答案

是的。如果没有显式的 super ,那么私有构造函数有一个隐式的 super()调用构造函数调用。在这方面,它与其他构造者没有什么不同。当然,为了编译,超类必须有一个从类中可见的无参数构造函数。

Yes. The private constructor has an implicit super() call if there is not explicit super or this constructor call. In this respect, it is no different from other constructors. Naturally, for this to compile, the superclass has to have a no-args constructor that is visible from the class.

但是,如果构造函数是 private ,它不能从子类中调用 ...或者除了类本身之外的任何其他代码。

However, if a constructor is private, it cannot be called from a subclass ... or from any other code apart from the class itself.

这篇关于类中的私有构造函数用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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