在这种情况下,调用super的构造函数是否多余? [英] Is calling super's constructor redundant in this case?

查看:57
本文介绍了在这种情况下,调用super的构造函数是否多余?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为,当创建带有子类的对象时,我们需要显式地使用 super(arguments list)来调用超类的构造函数.但是我做了一个实验,意识到即使使用 super(),即使不使用,超类的构造函数也会被自动调用.这是真的?

I always thought that when creating an object with a sub-class, we need to explicitly use super(arguments list) to call the constructor of the super class. However I did an experiment and realize that even without using the super(), the super class's constructor will be called automatically. Is this true?

如果这是真的,什么时候 super()是多余的,什么时候不是?

If this is true, when is super() redundant and when it is not?

class Parent
{
    public Parent()
    {
        System.out.println("Super Class");
    }           

}

class Child extends Parent
{
    public Child()
    {
        super();   //Is this redundant?
        System.out.println("Sub Class");
    }   
}

public class TestClass
{
    public static void main(String[] args) 
    {
        new Child();
    }
}

输出(子类中的 With super(); ):

Super Class
Sub Class

输出(子类中的 super(); ):

Super Class
Sub Class

推荐答案

如有疑问,请始终咨询

When in doubt, always consult the specification:

如果构造函数主体不是以显式构造函数调用开始的,并且要声明的构造函数不是原始类Object的一部分,则构造函数主体将以超类构造函数调用" super();隐式开始".code>",它的直接超类的构造函数的调用不带参数.

If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

这篇关于在这种情况下,调用super的构造函数是否多余?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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