2010-01-13 101 views
21

hei。該語言是java。 我想擴展這個構造函數有參數的類。java,擴展類與主類的構造函數有參數

這是主類

public class CAnimatedSprite { 
    public CAnimatedSprite(String pFn, int pWidth, int pHeight) { 
    } 
} 

這是子類

public class CMainCharacter extends CAnimatedSprite { 

    //public void CMainCharacter:CAnimatedSprite(String pFn, int pWidth, int pHeight) { 
    //} 
} 

我怎樣寫正確的語法? 和錯誤是「構造函數不能應用於給定的類型」

回答

36

您可以定義您的構造函數所需的任何參數,但有必要調用超類的一個構造函數作爲自己的構造函數的第一行。這可以使用super()super(arguments)完成。

public class CMainCharacter extends CAnimatedSprite { 

    public CMainCharacter() { 
     super("your pFn value here", 0, 0); 
     //do whatever you want to do in your constructor here 
    } 

    public CMainCharacter(String pFn, int pWidth, int pHeight) { 
     super(pFn, pWidth, pHeight); 
     //do whatever you want to do in your constructor here 
    } 

} 
+0

它的工作原理。謝謝。解決了這個語法問題。 – r4ccoon 2010-01-13 12:21:47

+0

如果我在根類中有多個構造函數,該怎麼辦?我需要爲我的擴展類中的每個人做super()嗎? – sammiwei 2012-01-30 19:07:46

3

構造函數的第一個語句必須是對超類構造函數的調用。語法是:

super(pFn, pWidth, pHeight); 

它是由你來決定,你是否希望你的類的構造函數具有相同的參數,只是將它們傳遞給父類的構造:

public CMainCharacter(String pFn, int pWidth, int pHeight) { 
    super(pFn, pWidth, pHeight); 
} 

或者通過什麼的,像:

public CMainCharacter() { 
    super("", 7, 11); 
} 

而且不指定構造返回類型。這是非法的。

1
public class CAnimatedSprite { 
    public CAnimatedSprite(String pFn, int pWidth, int pHeight) { 
    } 
} 


public class CMainCharacter extends CAnimatedSprite { 

    // If you want your second constructor to have the same args 
    public CMainCharacter(String pFn, int pWidth, int pHeight) { 
     super(pFn, pWidth, pHeight); 
    } 
}