子类的构造函数默认调用父类的空参构造函数

本文详细解析了Java中子类构造器如何调用父类构造器的过程,特别是在父类缺少无参构造器时,子类构造器如何通过this或super语句明确调用特定构造器,避免编译错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class Wolf extends Animal {
	public Wolf() {
		super("熊大",2);
		System.out.println("wolf无参构造器");
	}
	public static void main(String[] args) {
		new Wolf();
	}
}
class Animal extends Creature{
	public Animal(){
		System.out.println("Animal 无参构造器");
	}
	public Animal(String name) {
		System.out.println("Animal 有参构造器,name:"+name);
	}
	public Animal(String name,int age) {
		this(name);
		System.out.println("Animal两个参数构造器,其age:"+age);
	}
}
class Creature{
	public Creature() {
		System.out.println("Creature 无参构造器");
	}
}

执行结果:

Creature 无参构造器
Animal 有参构造器,name:熊大
Animal两个参数构造器,其age:2
wolf无参构造器

 

 

如果Creature没有定义无参的构造器,而只定义了有参构造器,Animal构造器会报错:Implicit super constructor Creature() is undefined. Must explicitly invoke another constructor,编译不通过。

public class Wolf extends Animal {
	public Wolf() {
		super("熊大",2);
		System.out.println("wolf无参构造器");
	}
	public static void main(String[] args) {
		new Wolf();
	}
}
class Animal extends Creature{
	public Animal(){
		System.out.println("Animal 无参构造器");
	}
	public Animal(String name) {
		System.out.println("Animal 有参构造器,name:"+name);
	}
	public Animal(String name,int age) {
		this(name);
		System.out.println("Animal两个参数构造器,其age:"+age);
	}
}
class Creature{
	/*public Creature() {
		System.out.println("Creature 无参构造器");
	}*/
	public Creature(String name) {
		System.out.println("Creature 无参构造器"+name);
	}
}

结论:

子类中所有的构造默认都会访问父类中空参数构造

父类中没有空参数的构造,子类的构造必须通过this(参数列表)或者super(参数列表)语句指定调用本类或者父类中相应的构造,且必须放在构造器的第一行

如果子类构造中既未显式调用父类或本类的构造,且父类中又没有无参的构造,则编译出错

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值