[英]Need argument-less constructor for subclass, but superclass doesn't have it
這里的OOP初學者...我有一個名為Rectangle的超類,該類具有一個接受int height和int width作為參數的構造函數。 我的任務是創建一個改進的Rectangle子類,除其他外,它配備不需要參數的構造函數。
那么,如何做到這一點而又不弄亂超類呢?
public class BetterRectangle extends Rectangle
{
public BetterRectangle(int height, int width)
{
super(height,width);
}
public BetterRectangle()
{
width = 50;
height = 50;
}
}
這給了我“未定義超級隱式構造函數”。 顯然,我需要調用超類構造函數。 但是用什么呢? 只是隨機值,以后會被覆蓋嗎?
嘗試這個:
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()或this()的調用。 如果沒有對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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.