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

父类:


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

 欢迎加我的qq技术群425783133

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值