继承java-bank帐户(java)

时间:2018-06-18 11:21:06

标签: java inheritance

我正在开发一个有5个类的继承银行帐户。在其中一个类(InterestFreeDeposit)中,应该创建一个至少10美元的帐户。我该如何编写这部分的代码? 这是我到目前为止所做的事情:

超类:

import java.util.Scanner;
import java.io.FileReader;
public class Account {
    private String owner;
    private double balance;
    private int accountNumber;
    private double interestRate;
        public Account( String owner,double balance, int accountNumber , double interestRate){
            this.balance=balance;
            this.owner=owner;
            this.accountNumber=accountNumber;
            this.interestRate=interestRate;
        }
        public void deposit(double amount) {
                if(amount>0) {
                    this.balance+=amount;
                }

        }
        public void withdraw(double amount) {
                if(amount>0 && balance>=amount) {
                    this.balance-=amount;
                }
        }
        public double getBalance() {
            return balance;
        }
        public void setBalance(double amount) {
            this.balance = amount;
        }

        public String getOwner() {
            return owner;
        }


public void setOwner(String owner) {
            this.owner = owner;
        }
        public int getAccountNumber() {
            return accountNumber;
        }
        public void setAccountNumber(int accountNumber) {
            this.accountNumber = accountNumber;
        }
        public double getInterestRate() {
            return interestRate;
        }
        public double setInterestRate(double interestRate) {
            //System.out.println("Enter the period(month):");

            return this.balance +=balance * interestRate/100;
        }

子类(InterestFrreClass):

public class InterestFreeDeposit extends Account {
public InterestFreeDeposit(String owner, double balance, int accountNumber, double interestRate) {
    super(owner, balance, accountNumber, interestRate);
    // TODO Auto-generated constructor stub
}
public void interest() {
    super.setInterestRate(0.0) ;


    }

}

2 个答案:

答案 0 :(得分:1)

您需要在设置值时添加检查,在这种情况下会在InterestFreeDeposit的构造函数中进行。问题是当值低于10时你想如何反应。您可以抛出IllegalArgumentException

public InterestFreeDeposit(String owner, double balance, int accountNumber, double interestRate) {
    super(owner, balance, accountNumber, interestRate);
    if(balance < 10){
        throw new IllegalArgumentException("balance must be at least 10");
    }
}

这种方法的问题是IllegalArgumentException是一个未经检查的异常,这意味着构造函数的调用者在被抛出时不会被强制处理它。

答案 1 :(得分:0)

您可以在子类constuctor中使用三元运算符来默认为10.0最小值:

public class InterestFreeDeposit extends Account {
     public InterestFreeDeposit(String owner, double balance, int accountNumber, double interestRate) {
         super(owner, balance < 10.0 ? 10.0 : balance, accountNumber, interestRate);
     }
}

可以将三元运算符视为内联运算符。所以你有以下结构:

condition ? condition is true : condition is false

在上面的代码段中,它只检查提供的余额是否低于10.0。如果它只是将它设置为10,否则传递它:

balance < 10.0 ? 10.0 : balance