父类:
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