黑马程序员_java子类构造函数的执行过程

------- android培训java培训、期待与您交流! ----------

java是面向对象的程序设计语言,有封装、继承和多态三大特性。这里我们来讲一下类的继承中关于子类构造函数的执行细节。

class Parent{
	Parent(){
		System.out.println("Parent");
	}
}
class Child extends Parent{
	Child(){
		System.out.println("Child");
	}
}
class Demo{
	public static void main(String[] args){
		Child  ch = new Child();
	}
}

上面的代码中,Child类是Parent类的子类。当我们创建Child对象ch。Child的构造函数被调用。

直观上,我们以为结果是

Child

但是运行结果是

Parent

Child

这里就体现了子类在创建对象时首先调用父类构造函数的过程:

1. 创建Child对象ch

2. Child进入构造函数Child()

3. 程序跳转到父类构造函数Parent()执行,打印出Parent

4. Parent()执行结束后,跳回到Child()执行,打印出Child


这个过程显示出其实在Child()函数体的第一行省略了一行代码:super(),用来调用空参的父类构造函数。

Child(){
	super();
	System.out.println("Child");
}

当然如果我们想调用父类的有参构造方法时,可以用super(参数值)

class Parent{
	protected String name;
	Parent(){
		System.out.println("Parent_no_parameter");
	}
	Parent(String name){
		this.name = name;
		System.out.println("Parent_has_parameter");
	}
}
class Child extends Parent{
	private int age;
	Child(){}
	Child(String name, int age){
		super(name);
		this.age = age;
		System.out.println("Child_has_parameter");
	}
}
class Demo{
	public static void main(String[] args){
		Child  ch = new Child("Lily", 25);
	}
}

上面的代码输出是

Parent_has_parameter

Child_has_parameter

从结果可以看出,

1. 子类构造方法Child(String name, int age)被调用,

2. 第一句super(name)跳到Parent的构造方法Parent(String name)中,打印出Parent_has_parameter

3. 跳回到Child(String name, int age)中继续向下执行,打印出Child_has_parameter

所以说这个过程不会再去找父类的空参构造函数。


下面这种情况,当子类构造函数用this()引用自身其他构造函数时,是不能再用super的,当然也没有前面提到的空参默认super()。同样的,当我们用到了super时,this()就不能再用。super()和this()只能放在构造函数第一行,不能同时出现。下面代码是错误的。

class Parent{
	protected String name;
	Parent(){
		System.out.println("Parent_no_parameter");
	}
	Parent(String name){
		this.name = name;
		System.out.println("Parent_has_parameter");
	}
}
class Child extends Parent{
	private int age;
	Child(){
		System.out.println("Child_no_parameter");
	}
	Child(String name, int age){
		this();
		super(name);
		this.age = age;
		System.out.println("Child_has_parameter");
	}
}
class Demo{
	public static void main(String[] args){
		Child  ch = new Child("Lily", 25);
	}
}
------- Windows Phone 7手机开发.Net培训、期待与您交流! -------
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值