我有一個名爲LotteryTicket
的類,它有3個子類:Pick4
,Pick5
和Pick6
。我希望能夠調用方法public void pickNumbers()
曾經被調用,將能夠識別正在使用哪個LotteryTicket子類並請求適量的參數(即在Pick5
的實例中調用pickNumbers()
將要求5個整數)。如何從Java中的繼承方法調用特定的重寫方法?
我已嘗試通過在LotteryTicket
類4,圖5和6提供public void pick4Numbers(int firstPick, int secondPick, int thirdPick, int fourthPick)
,以及具有該pickNumbers()
方法調用基於字段pickAmount
適當的方法(其將得到重寫)來解決這個問題。不幸的是,這將需要提供參數。
這裏是LotteryTicket
類:
public class LotteryTicket
{
protected int pickAmount;
protected boolean isRandom;
protected ArrayList<Integer> numbersPicked;
protected Date datePurchased;
protected SimpleDateFormat sdf;
public LotteryTicket(int pickAmount, boolean isRandom)
{
// INITIALIZATION OF VARIABLES
this.pickAmount = pickAmount;
this.isRandom = isRandom;
// CONSTRUCTION OF ARRAYLIST
numbersPicked = new ArrayList(pickAmount);
}
/**
* The number pick method for ALL subclasses. Running this method will run the appropriate pickxNumbers
* method, where x is the pickAmount.
*
*/
public void pickNumbers()
{
if(pickAmount == 4){
pick4Numbers(int firstPick, int secondPick, int thirdPick, int fourthPick)
}
if(pickAmount == 5){
pick5Numbers(int firstPick, int secondPick, int thirdPick, int fourthPick, int fifthPick)
}
if(pickAmount == 6){
pick6Numbers(int firstPick, int secondPick, int thirdPick, int fourthPick, int fifthPick, int sixthPick)
}
}
/**
* The number pick method for the Pick4 subclass.
*
*/
public void pick4Numbers(int firstPick, int secondPick, int thirdPick, int fourthPick)
{
}
Pick4
類:
public class Pick4 extends LotteryTicket
{
/**
* Constructor for objects of class Pick4
*/
public Pick4(boolean isRandom)
{
super(4, isRandom);
}
/**
* Overloaded pick4Numbers() method. Depending on the ticket type, the amount of picks will vary.
* For example, Pick4 tickets will only ask for 4 int values, Pick5 tickets will ask for 5, etc.
*
*@param int firstPick
*@param int secondPick
*@param int thirdPick
*@param int fourthPick
*/
public void pick4Numbers(int firstPick, int secondPick, int thirdPick, int fourthPick)
{
numbersPicked.add(new Integer(firstPick));
numbersPicked.add(new Integer(secondPick));
numbersPicked.add(new Integer(thirdPick));
numbersPicked.add(new Integer(fourthPick));
}
接受可變參數' public void pick(int ... args)'並且拋出IllegalArgumentException如果number無效 –
你的代碼是否被編譯? – CKing
@ChetanKinger如果OP按照他們的說法聲明'pick5Numbers'和'pick6Numbers',爲什麼不呢? –