【发布时间】:2015-05-02 19:58:24
【问题描述】:
我有一个名为 LotteryTicket 的类,它有 3 个子类:Pick4、Pick5 和 Pick6。我希望能够调用方法public void pickNumbers()where 一旦被调用,将能够识别正在使用哪个 LotteryTicket 子类并要求适当数量的参数(即在 Pick5 的实例中调用 pickNumbers() 会问5 个整数)。
我试图通过在 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 -
你的代码能编译吗?
-
@ChetanKinger 如果 OP 像他们所说的那样声明了
pick5Numbers和pick6Numbers,为什么不呢? -
@SashaSalauyou
if(pickAmount == 4){ pick4Numbers(int firstPick, int secondPick, int thirdPick, int fourthPick) }. -
选择值从何而来? (
firstPick,secondPick, ...)
标签: java inheritance parameters overriding overloading