Java:为什么我的类会自动从超类继承构造函数? [英] Java: Why does my class automatically inherits constructor from superclass?
问题描述
当我尝试此问题底部的代码时,输出为:
When I try the code on the bottom of this question, the output is:
a a b a b c
因此,这意味着B和C中的构造函数从其超类中调用构造函数。但为什么?
我认为超类的构造函数仅在与super()函数一起使用时才被调用:
So this means that the constructor from B and C call the constructors from their superclasses. But why? I thought that the superclass' constructor only get's called when used with the super() function like this:
public sportscar(String name, int weight, int topspeed){
super(name, weight);
this.setTopspeed(topspeed);
}
但是如果它自动从其扩展的类中继承构造函数,为什么我们会使用super()函数吗?我知道正常的方法会自动扩展到那里的子类,但是我认为构造函数是不同的。
But if it automatically takes over the constructor from the classes they extend from, why would we use the super() function? I know that normal methods extend to there sub-classes automaticaly, but I thought that the constructor was different.
如果有人可以帮我解决这个问题,非常感谢!
If anyone can clear this out for me, thanks a lot!
代码:
public class App {
public static void main(String[] args) {
new A();
new B();
new C();
}
}
public class A {
public A(){
System.out.println("a ");
}
}
public class B extends A {
public B(){
System.out.println("b ");
}
}
public class C extends B {
public C(){
System.out.println("c ");
}
}
推荐答案
此行为由JLS强制执行( §8.8.7。构造函数主体):
This behaviour is mandated by the JLS (§8.8.7. Constructor Body):
如果构造函数主体不以显式构造函数调用和构造函数开头被声明的对象不是原始类
Object
的一部分,则构造函数体隐式地以超类构造函数调用super(); $ c开头$ c>,其直接超类的构造函数的调用,该构造函数不带参数。
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.
这篇关于Java:为什么我的类会自动从超类继承构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!