Discuss / Java / 变成抽象类 不仅自己 不能 new 对象 子类还要多写构造方法

变成抽象类 不仅自己 不能 new 对象 子类还要多写构造方法

Topic source

Income 

/**
* 定义抽象类Income
*/
public abstract class Income {

protected double income;

public abstract double getTax();

}

RoyaltyIncome 

/**
* 稿费收入税率是20%
*/
public class RoyaltyIncome extends Income {

public RoyaltyIncome(double income) {
this.income = income;
}

@Override
public double getTax() {
return income * 0.2; // 税率20%
}

// TODO

}

SalaryIncome 

public class SalaryIncome extends Income {

public SalaryIncome(double income) {
this.income = income;
}

@Override
public double getTax() {
if (income <= 5000) {
return 0;
}
return (income - 5000) * 0.2;
}

// TODO

}

Main

public class Main {

public static void main(String[] args) {
// TODO: 用抽象类给一个有工资收入和稿费收入的小伙伴算税:
Income[] incomes = new Income[]{new SalaryIncome(7500), new RoyaltyIncome(12000)};
double total = 0;
// TODO:
total = totalTax(incomes);
System.out.println(total);
}

public static double totalTax(Income... incomes) {
double total = 0;
for (Income income : incomes) {
total = total + income.getTax();
}
return total;
}
}

🌙

#2 Created at ... [Delete] [Delete and Lock User]

抽象类,也可以有构造方法,还可以继承

public Income(double income) {
this.income = income;
}

余文礼

#3 Created at ... [Delete] [Delete and Lock User]

好牛


  • 1

Reply