2011-11-08 46 views
22

我有一個擴展類「ParentClass」的類「ChildClass」。我不想完全替換父類的構造函數,而是先調用父類的構造函數,然後再做一些額外的工作。在Java的子類中使用父構造函數

我相信默認情況下調用父類的0參數構造函數。這不是我想要的。我需要用參數調用構造函數。這可能嗎?

我試圖

this = (ChildClass) (new ParentClass(someArgument)); 

但是,這並不工作,因爲你不能修改「本」。

+2

['super'](http://download.oracle.com/javase/tutorial/java/IandI/super.html)。 – birryree

+0

檢查此解決方案:http://leepoint.net/notes-java/oop/constructors/constructor-super-example.html – Raihan

回答

48

你可以在子的構造函數中用「super」引用父類的構造函數。

public class Child extends Parent { 
    public Child(int someArg) { 
     super(someArg); 
     // other stuff 
    } 
    // .... 
} 
+2

啊哈,謝謝。我真的應該閱讀我編寫的Java編程書,它會阻止我問這樣的愚蠢問題。 –

+6

使用super()對父進程構造函數的調用需要是您的子構造函數中的第一次調用。 – bakoyaro

5

您應該使用super關鍵字。

public ChildClass(...) { 
    super(...); 
} 
9

來調用特定的父類的構造函數,把super(param1, param2, ...)作爲兒童類的構造函數體的第一條語句。在Java中是

相關問題