为什么总是调用超类构造函数 [英] Why is super class constructor always called

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

问题描述

我有以下2个课程

public class classA {
    classA() {
        System.out.println("A");
    }
}

class classB extends classA {
    classB() {
        System.out.println("B");
    }
}

然后运行

classA c = new classB();

classB c = new classB(); 

总是给

A
B

为什么会这样?乍一看,无论哪种情况,我都将假定仅调用classB构造函数,因此唯一的输出将是

Why is this happening? At first glance, in either scenario, I would assume that only the classB constructor would be called and thus the only output would be

B

但这显然是错误的.

推荐答案

这就是Java的工作方式.在调用子类的构造函数之前,将通过Object一直调用父类的构造函数.

That is how Java works. The constructors of the parent classes are called, all the way up the class hierarchy through Object, before the child class's constructor is called.

引用文档:

使用super(),将调用超类无参数构造函数.使用super(parameter list)时,将调用具有匹配参数列表的超类构造函数.

With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.

注意: 如果构造函数未明确调用超类构造函数,则Java编译器会自动向超类的无参数构造函数插入调用 .如果超类没有无参数构造函数,则会出现编译时错误. Object确实具有这样的构造函数,因此,如果Object是唯一的超类,则没有问题.

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

如果子类构造函数显式或隐式调用其超类的构造函数,则您可能会认为将调用整个构造函数链,一直返回到Object的构造函数.实际上就是这种情况.它称为构造函数链接,当类下降很长时,您需要意识到这一点.

If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that there will be a whole chain of constructors called, all the way back to the constructor of Object. In fact, this is the case. It is called constructor chaining, and you need to be aware of it when there is a long line of class descent.

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

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