Discuss / Java / 11
public class InterfaceDemo {    public static double totalTax(Income2[] incomes) {        double total = 0;        for (Income2 income : incomes) {            total += income.getTax2();        }        return total;    }    public static void main(String[] args) {        // TODO: 用接口给一个有工资收入和稿费收入的小伙伴算税:        // 接口可以实例化吗?接口不可以实例化,但是接口对象可以指向它的实现类对象。        Income2[] incomes = new Income2[]{new SalaryIncome2(7500), new RoyaltyIncome2(12000)};        // TODO:        System.out.println(totalTax(incomes));    }}interface Income2 {    double getTax2();}class RoyaltyIncome2 implements Income2 {    protected double income2;    public RoyaltyIncome2(double income) {        this.income2 = income;    }    @Override    public double getTax2() {        return income2 * 0.2;    }}class SalaryIncome2 implements Income2 {    protected double sincome;    public SalaryIncome2(double income) {        this.sincome = income;    }    @Override    public double getTax2() {        if (sincome <= 5000) {            return 0;        } else {            return (sincome - 5000) * 0.2;        }    }}

  • 1

Reply