java继承时候类的执行顺序问题

子类在继承父类后,创建子类对象会首先调用父类的构造函数,先执行父类的构造函数,然后再执行子类的构造函数,如下所示:


class Father{
	public Father(){
		System.out.println("I am father");
	}
}
public class Child extends Father{
	public Child(){	
		System.out.println("I am child");
	}
	public static void main(String[] args) {
		Father f=new Father();
		Child c=new Child();
	}
}

当父类有带参数的构造函数时,子类默认是调用不带参数的构造函数,如下所示:


class Father{
	public Father(){
		System.out.println("I am father");
	}
	public Father(String name){
		System.out.println("I am father,My name is "+name);
	}
}
public class Child extends Father{
	public Child(){	
		System.out.println("I am child");
	}
	public static void main(String[] args) {
		Father f=new Father("Apache");
		Child c=new Child();
	}
}

若想子类调用父类带参数的构造函数,需要用super()函数申明,如下:

class Father{
	public Father(){
		System.out.println("I am father");
	}
	public Father(String name){
		System.out.println("I am father,My name is "+name);
	}
}
public class Child extends Father{
	public Child(){	
		super("Apache");
		System.out.println("I am child");
	}
	public static void main(String[] args) {
		Father f=new Father("Apache");
		Child c=new Child();
	}
}


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值