java基础练习题

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类

  • 2
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值