Java 类的继承练习题
适用于java初学者
1、
写一个名为Account的类模拟账户。该类的属性和方法如下图所示。该类包括的属性:账号id,余额balance,年利率annualInterestRate;
包含的方法:访问器方法(getter和setter方法),
返回月利率的方法getMonthlyInterest(),取款方法withdraw(),存款方法deposit()。
Account
private int id
private double balance
private double annualInterestRate
public Account (int id, double balance, double annualInterestRate )
public int getId()
public double getBalance()
public double getAnnualInterestRate()
public void setId( int id)
public void setBalance(double balance)
public void setAnnualInterestRate(double annualInterestRate)
public double getMonthlyInterest()
public void withdraw (double amount)
public void deposit (double amount)
写一个用户程序测试Account类。在用户程序中,创建一个账号为1122、余额为20000、年利率4.5%的Account对象。使用withdraw方法提款30000元,并打印余额。
再使用withdraw方法提款2500元,使用deposit方法存款3000元,然后打印余额和月利率。
提示:在提款方法withdraw中,需要判断用户余额是否能够满足提款数额的要求,如果不能,应给出提示。
运行结果如图所示:
解答代码:
//首先定义一个Account类模拟账户
public class Account {
//定义类的属性
private int id;// 账号
protected double balance;// 余额
private double annualInterstRate;// 年利率
public Account(int id, double balance, double annualInterstRate) {
super();
this.id = id;
this.balance = balance;
this.annualInterstRate = annualInterstRate;
}
// 返回月利率的方法
public double getMonthlyInterest() {
return annualInterstRate / 12;
}
// 取款方法
public void withdraw(double amount) {
if (amount > balance) {
System.out.println("余额不足");
System.out.println("余额为:" + balance);
} else {
balance = balance - amount;
System.out.println("余额为:" + balance);
}
}
// 存款方法
public void deposit(double amount) {
balance = balance + amount;
System.out.println("余额为:" + balance);
}
public int getId() {// getter和setter方法
return id;
}
public void setId(int id) {
this.id = id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getAnnualInterstRate() {
return annualInterstRate;
}
public void setAnnualInterstRate(double annualInterstRate) {
this.annualInterstRate = annualInterstRate;
}
}
定义一个CheckAccount类继承Account类
public class CheckAccount extends Account {
private double overdraft; //