假设在银行定期存款分半年期和一年期两种。如果是半年定期存款利息率为175;如果是一年定期存款利息率为225。无论哪种存款在得到利息后还要交利息所得税5。根据不同的存款金额分别计算存款半年和一年相应的利息。 要求: 1设计一个存款抽象类Cash成员变量包括存款金额amount、利息率interest和利息所得税tax为最终类成员方法只有抽象方法calculate用来计算利息; 2定义两个类HalfC
抽象类Cash:
public abstract class Cash {
protected double amount; // 存款金额
protected double interest; // 利息率
protected double tax; // 利息所得税
public Cash(double amount, double interest, double tax) {
this.amount = amount;
this.interest = interest;
this.tax = tax;
}
public abstract double calculate(); // 计算利息的抽象方法
}
HalfCash类:
public class HalfCash extends Cash {
public HalfCash(double amount, double interest, double tax) {
super(amount, interest, tax);
}
@Override
public double calculate() {
double interest = amount * this.interest * 0.5; // 半年利息
double afterTax = interest * (1 - this.tax); // 扣除利息所得税后的利息
return afterTax;
}
}
FullCash类:
public class FullCash extends Cash {
public FullCash(double amount, double interest, double tax) {
super(amount, interest, tax);
}
@Override
public double calculate() {
double interest = amount * this.interest; // 一年利息
double afterTax = interest * (1 - this.tax); // 扣除利息所得税后的利息
return afterTax;
}
}
测试代码:
public class Test {
public static void main(String[] args) {
Cash halfCash = new HalfCash(1000, 0.0175, 0.05);
Cash fullCash = new FullCash(1000, 0.0225, 0.05);
double halfInterest = halfCash.calculate();
double fullInterest = fullCash.calculate();
System.out.println("半年定期存款利息:" + halfInterest);
System.out.println("一年定期存款利息:" + fullInterest);
}
}
输出结果:
半年定期存款利息:8.28125
一年定期存款利息:20.4375
原文地址: https://www.cveoy.top/t/topic/br0Y 著作权归作者所有。请勿转载和采集!