java 构造函数 自动,Java:为什么我的类会自动从超类继承构造函数?

When I try the code on the bottom of this question, the output is:

a a b a b c

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);

}

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!

Code:

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 ");

}

}

解决方案

This behaviour is mandated by the JLS (§8.8.7. Constructor Body):

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值