Discuss / Java / 练习

练习

Topic source

狠美味2013

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

/**

 * 多态/抽象类/接口

 * 

 * @author Administrator

 * 

 */

public class PolymorphicExample {

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;

}

}

/**

 * 收入,定义接口Income

 * 

 * @author Administrator

 * 

 */

public interface Income {

double getTax();

}

/**

 * 稿费收入税率是20%

 * 

 */

public class RoyaltyIncome implements Income {

// TODO

public double income;

public RoyaltyIncome(double income) {

this.income = income;

}

@Override

public double getTax() {

return income * 0.2; // 税率20%

}

}

/**

 * 工资收入

 * 

 * @author Administrator

 * 

 */

public class SalaryIncome implements Income {

public double income;

public SalaryIncome(double income) {

this.income = income;

}

@Override

public double getTax() {

if (income <= 5000) {

return 0;

}

return (income - 5000) * 0.2;

}

}


  • 1

Reply