多态
多态是指,针对某个类型的方法调用,其真正执行的方法取决于运行时期实际类型的方法,对某个类型调用某种方法,执行的实际方法可能是某个子类的覆写方法。
这种具有不确定性质的调用方法有什么用呢?
请看下方代码
public static void main(String[] args) {
// 给一个有普通收入、工资收入和享受国务院特殊津贴的小伙伴算税:
Income[] incomes = new Income[] {
new Income(3000),
new Salary(7500),
new StateCouncilSpecialAllowance(15000)
};
System.out.println(totalTax(incomes));
}
public static double totalTax(Income... incomes) {
double total = 0;
for (Income income: incomes) {
total = total + income.getTax();
}
return total;
}
}
class Income {
protected double income;
public Income(double income) {
this.income = income;
}
public double getTax() {
return income * 0.1; // 税率10%
}
}
class Salary extends Income {
public Salary(double income) {
super(income);
}
@Override
public double getTax() {
if (income <= 5000) {
return 0;
}
return (income - 5000) * 0.2;
}
}
class StateCouncilSpecialAllowance extends Income {
public StateCouncilSpecialAllowance(double income) {
super(income);
}
@Override
public double getTax() {
return 0;
}
这时候totalTax()方法只需要和Income打交道即可,不需要知道Income父类所继承的子类的存在,就可以加酸楚正确的所需要的税收。
如果要新增一种稿费收入,煮需要从Income父类中派生即可,然后正确的覆写getTax()方法,无需修改任何代码,这就是多态的好处。