1. 程式人生 > >Java中建構函式的繼承問題

Java中建構函式的繼承問題

建構函式不會被繼承,只是被子類呼叫而已

  1. 子類所有的建構函式預設呼叫父類的無參建構函式。
  2. 子類的某個建構函式想呼叫父類的其他的帶引數的建構函式,第一行人為新增super(val1,val2[,val3…]).
  3. super指代父類物件,可以在子類中使用 super.父類方法名();呼叫父類中的方法。
class Bee00{
	int id;		//蜜蜂的唯一標識
	int x,y;	//蜜蜂現在所處的位置座標(最小單位:畫素)
	int honey;	//當前蜜蜂採集蜂蜜的數量(單位:mg)
	 //最好加上下面這一行
	// public Bee00(){}
	
    public Bee00(int id,int x,int y)
    {   
		this.id = id;
		this.x = x;
		this.y = y;
		this.honey = 0;
		System.out.println("Bee: "+id+" come from ("+x+","+y+")");
    }

	public void showHoney()
	{
		System.out.println("Bee: "+id+" has ("+honey+"mg) honey ");
	}
	
}
public class Bee01 extends Bee00{
	public Bee01(int id,int x,int y){
		super(id,x,y);
	}
	/*
	public Bee01(int id){
		this.id= id;
	}
	*/
	public static void main(String[] args)
	{
		Bee00 bee1 = new Bee01(1);
		Bee00 bee2 = new Bee01(2,100,100);
		System.out.println(bee1);
		System.out.println(bee2);
	}
}
D:\JavaLesson\第一次課資料>javac Bee01.java
Bee01.java:26: 錯誤: 無法將類 Bee00中的構造器 Bee00應用到給定型別;
        public Bee01(int id){
                            ^
  需要: int,int,int
  找到: 沒有引數
  原因: 實際引數列表和形式引數列表長度不同
1 個錯誤

因為父類Bee00沒有無參的建構函式,子類如果想有自己的建構函式,必須現在建構函式第一行顯式呼叫super(args); 所以一般會在父類中加上無參的建構函式。這樣的話,子類建立自己的建構函式時就可以不用顯式呼叫super(…);