有关Constructor call must be the first statement in a constructor的问题

class TestA {

public TestA() {

System.out.println("A");

}

}

class TestB extends TestA {

public TestB(int i) {

super();

this();

}

public TestB() {

System.out.println("B")

}

}

public class Test {

public static void main(String[] ars) {

new TestB(1);

}

}

super()和this ()不能共存,否则编译时会报异常。

Constructor call must be the first statement in a constructor

换句话说就是super()和this ()都必须在构造方法的第一行。

this(有参数/无参数) 用于调用本类相应的构造函数

super(有参数/无参数) 用于调用父类相应的构造函数

而且在构造函数中,调用必须写在构造函数定义的第一行,不能在构造函数的后面使用。

一个构造函数定义中不能同时包括this调用和super调用,如果想同时包括的话,可以在this()调用的那个构造函数中首先进行super()调用。也可以把TestB()这个方法修改成非构造方法,在构造方法TestB(int i)中调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值