Why is super class constructor always called [duplicate]

◇◆丶佛笑我妖孽 提交于 2019-12-28 03:04:29

问题


I have the following 2 classes

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

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

and then running

1

classA c = new classB();

or

2

classB c = new classB(); 

always gives

A
B

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

but this is clearly wrong.


回答1:


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.

Quoting from the docs:

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

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.

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.




回答2:


Super class constructor is always called during construction process and it's guaranteed that super class construction is finished before subclass constructor is called. This is the case for most if not all the object oriented language. You could explicitly call super class constructor with parameter if you don't want to invoke the default constructor; otherwise such call is automated by compiler.




回答3:


There is no difference in both statements in terms of objects being constructed so you see same out put.

Just using a different reference type on left hand side while constructing same objects using new is not going to make any difference as far as object creation and constructor chaining is concerned.

Whatever difference is there among two of your statements is after objects get created.



来源:https://stackoverflow.com/questions/34488484/why-is-super-class-constructor-always-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!