1.如果子類沒有定義構(gòu)造方法,則調(diào)用父類的無參數(shù)的構(gòu)造方法,.
2.如果子類定義了構(gòu)造方法,不論是無參數(shù)還是帶參數(shù),在創(chuàng)建子類的對象的時候,首先執(zhí)行父類無參數(shù)的構(gòu)造方法,然后執(zhí)行自己的構(gòu)造方法。
3.如果子類調(diào)用父類帶參數(shù)的構(gòu)造方法,可以通過super(參數(shù))調(diào)用所需要的父類的構(gòu)造方法,切該語句做為子類構(gòu)造方法中的第一條語句。
4.如果某個構(gòu)造方法調(diào)用類中的其他的構(gòu)造方法,則可以用this(參數(shù)),切該語句放在構(gòu)造方法的第一條.
說白了:原則就是,先調(diào)用父親的.(沒有就默認(rèn)調(diào),有了就按有的調(diào),反正只要有一個就可以了.)
package test;
class Father{
String s = "Run constructor method of Father";
public Father(){
System.out.println(s);
}
public Father(String str){
s= str;
System.out.println(s);
}
}
class Son extends Father{
String s= "Run constructor method of son";
public Son(){
//實際上在這里加上super(),和沒加是一個樣的
System.out.println(s);
}
public Son(String str){
this();//這里調(diào)用this()表示調(diào)用本類的Son(),因為Son()中有了一個super()了,所以這里不能再加了。
s = str;
System.out.println(s);
}
public Son(String str1, String str2){
super(str1+" "+str2);//因為這里已經(jīng)調(diào)用了一個父類的帶參數(shù)的super("---")了,所以不會再自動調(diào)用了無參數(shù)的了。
s = str1;
System.out.println(s);
}
}
public class MyClass9 {
public static void main(String[] args){
Father obfather1 = new Father();
Father obfather2 = new Father("Hello Father");
Son obson1 = new Son();
Son obson2 = new Son("hello son");
Son obson3 = new Son("hello son","hello father");
}
}
===============
結(jié)果:
Run constructor method of Father
Hello Father
Run constructor method of Father
Run constructor method of son
Run constructor method of Father
Run constructor method of son
hello son
hello son hello father
hello son
|