使用超类中使用更多参数的Super类中的单个参数

时间:2017-12-19 19:22:26

标签: java

这可能是非常容易解决的问题,但我对Java很新,我在修复此错误时遇到了问题。我正在研究一台基本的自动取款机(我现在还不开心)。我有一个BankAccount类,一个Checking Account(扩展了bankAccount),一个savingsAccount类(也扩展了bankAccount)和一个User类。在我的CheckingAccount类中,我想使用我的SUPER类(bankAccount)中的一个参数," balance"但我不确定是否有只使用具有多个参数的构造函数中的一个参数的方法。如果是这样,任何线索如何?我收到错误:"没有为BankAccount找到合适的构造函数(双)......" 。到目前为止,这是我的代码,感谢您的帮助。

- BankAccount Class -

package atm;

public class BankAccount {
    public double balance; 
    public int accountNumber = 333220; 
    public User user;  
    public BankAccount(){
        balance = 0; 
    }

    public BankAccount(double balance, int accountNumber, User user){ 
        this.balance = balance;
        this.accountNumber = accountNumber; 
        this.user = user; 

    }

    public void accountNumber(){
        accountNumber++;
    }

    public int getAccountNumber(){
        return accountNumber;
    }

    public void deposit (double amount){
        balance += amount; 
    }

    public void withDraw(double amount) {
        balance -= amount;  
    }

    public double getBalance (){
        return balance;  
    }

    public void transfer( BankAccount other,double amount){
        withDraw(amount);
        other.deposit(amount); 
    }


}

- CheckingAccount Class -

package atm;

public class CheckingAccount extends BankAccount {
    private int transactionCount;
    private static final double transactionFees = 1.50; 
    private static final int freeTransactions = 5; 


    public CheckingAccount (double balance){
        super(balance); //HERE is where I am confused. I only need to use the "balance" 
        transactionCount = 0; 
    }
    public void deposit(double amount){
    transactionCount ++; 
    super.deposit(amount); 
    }

    public void withDraw(double amount){
    transactionCount ++; 
    super.withDraw(amount);
    }
    public void deductFees (){
    if (transactionCount > freeTransactions){
        double fees = transactionFees * (transactionCount - freeTransactions); 
        super.withDraw(fees);
    }
    transactionCount = 0; 
    }
}

非常感谢!

2 个答案:

答案 0 :(得分:1)

您需要在BankAccount.java中创建另一个构建函数,该构造函数仅初始化amount,如下所示

public BankAccount(double balance){ 
    this.balance = balance;
}

了解这里有多个Java构造函数

http://tutorials.jenkov.com/java/constructors.html

答案 1 :(得分:0)

由于CheckingAccountBankAccount,因此它必须包含BankAccount的所有属性,包括帐号和拥有它的User

基类需要派生类提供accountNumberuser,因此您应该更改构造函数以将此信息转发到super

public CheckingAccount (double balance, int accountNumber, User user){
    super(balance, accountNumber, user);
    transactionCount = 0; 
}

注1:在某些情况下,派生类可以对要传递给super的参数进行硬编码;这其中一种情况。

注2:考虑将BankAccount抽象化,并将其构造函数的可访问性从public更改为protected