2013-07-03 33 views
0

OOP初學者在這裏...我有一個名爲Rectangle的超類,它有一個接受int高度和int寬度作爲參數的構造函數。我的任務是創建一個改進的Rectangle子類,其中還包含一個不需要參數的構造函數。需要無參數的構造函數爲子類,但超類沒有它

那麼,我該怎麼做,而不會弄亂超類?

public class BetterRectangle extends Rectangle 
{ 
    public BetterRectangle(int height, int width) 
    { 
     super(height,width); 
    } 

    public BetterRectangle() 
    { 
      width = 50; 
      height = 50; 
    } 
} 

這給了我「隱式超級構造函數是未定義」。顯然我需要調用超類的構造函數。但是用什麼?只是隨機值,後來被覆蓋?

+0

另一個問題是您沒有寬度,高度的實例變量,因此分配也失敗。 – kosa

+2

@Nambari它們可以在'Rectangle'中定義爲非'private'成員。 – GriffeyDog

+0

@GriffeyDog:如果是這樣的話,我認爲使用構造函數重新設置值是多餘的權利? – kosa

回答

6

試試這個:

public BetterRectangle() 
{ 
     super(50, 50); // Call the superclass constructor with 2 arguments 
} 

或者:

public BetterRectangle() 
{ 
     this(50, 50); // call the constructor with 2 arguments of BetterRectangle class. 
} 

你不能使用你的代碼在構造函數中的第一行是在調用super()或()這個。如果沒有對super()或this()的調用,那麼調用是隱含的。您的代碼相當於:

public BetterRectangle() 
{ 
     super(); // Compile error: Call superclass constructor without arguments, and there is no such constructor in your superclass. 
     width = 50; 
     height = 50; 
} 
+0

當然,但如果我不想要矩形爲50x50,但有一些用戶定義的值? –

+1

這不就是其他ctor的用途嗎? – duffymo

+0

如果您不傳遞參數,用戶如何傳遞它們的值?在無參數構造函數中,您需要提供默認值。 – eternay

相關問題