<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">1、首先調用父類的無參構造函數(這個構造函數必定會被調用)</span>
2、調用子類的無參構造函數或帶參數的構造函數;
例:
1、聲明抽象類爺爺--Father_of_AbstractClass
public abstract class Father_of_AbstractClass {
protected Father_of_AbstractClass(){
System.out.println("this is Father_of_AbstractClass's narg-constructor");
}
protected Father_of_AbstractClass(int i){
System.out.println("this is Father_of_AbstractClass's narg-constructor");
}
}
public abstract class AbstractClass extends Father_of_AbstractClass{
protected int abstractField;
protected AbstractClass(){
this.abstractField = 0;
System.out.println("this is AbstractClass's narg-constructor,and abstractField = "+this.abstractField);
}
//若創建了帶參的構造函數,則無參的構造函數必須顯示的寫出來,否則會編譯不通過
protected AbstractClass(int i){
this.abstractField = i;
System.out.println("this is AbstractClass's arg-constructor,and abstractField = "+this.abstractField);
}
}
public class GrandChieldren extends AbstractClass {
public GrandChieldren(){
System.out.println("this is GrandChieldren's noargs-constructor");
}
public GrandChieldren(int i){
System.out.println("this is GrandChieldren's arg-constructor");
}
public static void main(String args[]){
/*
此處輸出
this is Father_of_AbstractClass's narg-constructor
this is AbstractClass's narg-constructor,and abstractField = 0
this is GrandChieldren's noargs-constructor
*/
<span style="color:#ff0000;"><strong>GrandChieldren e = new GrandChieldren();</strong></span>
/*
* this is Father_of_AbstractClass's narg-constructor
this is AbstractClass's narg-constructor,and abstractField = 0
this is GrandChieldren's arg-constructor
*表明實例化子類時,
*1、先調用父輩的無慘構造函數(遞歸至頂層父類),
*2、在調用子類的構造函數,根據有無參數選擇無參構造函數或帶參構造函數
*/
<span style="color:#ff0000;"><strong>GrandChieldren f = new GrandChieldren(3);</strong></span>
}
}
此外,抽象類的構造函數作用:
1、可初始化成員變量;
2、爲繼承自它的子類所使用;(子類B實例化時會自動調用父類A的默認構造函數,所以,我們最好給父類A提供一個無參數的構造函數,或者在B的構造函數中顯示的調用父類A的有參構造函數。super(parameter)
同時,抽象類不能被實例化,因爲抽象類是抽象出來的,不存在實際的實體。所以實例化一個抽象類是沒有意義的,因此面向對象程序設計機制禁止對象實例化。