Discuss / Java / 练习

练习

Topic source
public class Oop {
    public static void main(String[] args) {
        Income[] incomes = {
                new SalaryIncome(7500),
                new RoyaltyIncome(12000)
        };
        System.out.println(totalTax(incomes));
    }

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

abstract class Income {
    protected double income;
    public abstract double getTax();
}

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

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

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

    @Override
    public double getTax() {
        return this.income *0.1;
    }
}

  • 1

Reply