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培训、期待与您交流! -------