Java错误:构造函数类Transaction中的Transaction不能应用于给定的类型

时间:2018-04-07 16:19:08

标签: java class constructor

我正在尝试回答以下提示:

编写一个具体的类ZeroBalance,它扩展了抽象类Transaction,其adjustAccount方法使Account的余额设置为零。由于ZeroBalance类不使用amount参数,因此您的类应该有一个只接受两个参数的构造函数,它应该覆盖toString方法,以便不提任何数量。

我对编码很陌生,而且我对如何构造一个只带两个参数的构造函数感到困惑。

到目前为止,这是我的代码:

public class ZeroBalance extends Transaction
{
public ZeroBalance (String time, String date ) 
    {
        super(time, date);
    }



public boolean adjustAccount ( Account acc )
{
    acc.setBalance(0);
    return true;
}

}

以下是帐户类:

public class Account {
private String myName;
private double myBalance;

public Account ( String name, double balance )
{
    myName = name;
    myBalance = balance;
}

public String getName()
{
    return myName;
}

public void setName ( String name )
{
    myName = name;
}

public double getBalance()
{
    return myBalance;
}

public void setBalance( double balance )
{
    myBalance = balance;
}

public String toString()
{
    return "Account holder: " + myName + "; Current balance: $" + 
    myBalance;
}
}

这是Transaction类:

public abstract class Transaction {
private double myAmount;
private String myTime;
private String myDate;

public Transaction ( double amount, String time, String date )
{
    myAmount = amount;
    myTime = time;
    myDate = date;
}

public double getAmount()
{
    return myAmount;
}

public String getTime ()
{
    return myTime;
}

public String getDate()
{
    return myDate;
}

public String toString()
{
    return getClass().getName() + " " + myAmount + " " + myTime + " " + 
    myDate;
}

public abstract boolean adjustAccount ( Account acc );
}

1 个答案:

答案 0 :(得分:0)

与提到的jb-nizetshahaf一样,您在调用基类构造函数时遇到了缺少参数的问题。您可以按如下方式解决此问题:

public class ZeroBalance extends Transaction
{

private static final double ZERO_BALANCE_AMOUNT = 0.0;    

public ZeroBalance (String time, String date ) 
    {
        super(time, date,ZERO_BALANCE_AMOUNT);
    }
// ....
// ....
}

<强>然而

我实际上建议您在Transaction中添加另一个构造函数,如下所示:

public abstract class Transaction {

private static final double ZERO_AMOUNT = 0.0;

private double myAmount;
private String myTime;
private String myDate;

public Transaction ( String time, String date )
{
    myAmount = ZERO_AMOUNT;
    myTime = time;
    myDate = date;
}

似乎更优雅的恕我直言,因为这允许交易的未来扩展者也开始与零余额。