您的位置:首页 > 其它

子类与父类构造方法执行顺序

2013-03-10 22:36 369 查看
父类:

public class Father {

String s="this is father";

public Father(){

System.out.println(s);

}

public Father(String str){

s=str;

System.out.println(s);

}

}

1、子类有或无参数构造方法,都会调用父类无参构造方法。

public class Son extends Father{

String s="this is son";

public Son(){

System.out.println(s);

}

public Son(String str){

//this();

s=str;

System.out.println(s);

}

public Son(String str1,String str2){

//super(str1+" "+str2);

s=str1;

System.out.println(s);

}

}

public class ExtendCase {

public static void main(String args[]){

Father f1=new Father();

Father f2=new Father("Hello father ");

Son s1=new Son();//调用父类无参构造方法,然后调用子类无参构造方法;

Son s2=new Son("Hello son ");//调用父类无参构造方法,然后调用子类含参构造方法。

Son s3=new Son("Hello son","Hello father");//

}

}

结果:

this is father

Hello father

this is father

this is son

this is father

Hello son

this is father

Hello son

2,子类调用父类有参构造方法必须实现super。调用了父类有参数的构造方法不会再自动调用无参数的构造方法。

public class Son extends Father{

String s="this is son";

public Son(){

System.out.println(s);

}

public Son(String str){

this();

s=str;

System.out.println(s);

}

public Son(String str1,String str2){

super(str1+" "+str2);

s=str1;

System.out.println(s);

}

}

public class ExtendCase {

public static void main(String args[]){

Father f1=new Father();

Father f2=new Father("Hello father ");

Son s1=new Son();//调用父类无参构造方法,然后调用子类无参构造方法;

Son s2=new Son("Hello son ");//调用父类无参构造方法,然后调用子类含参构造方法。

Son s3=new Son("Hello son","Hello father");//

}

}

结果:

this is father

Hello father

this is father

this is son

this is father

this is son

Hello son

Hello son Hello father

Hello son
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐