Discuss / Java / 练习

练习

Topic source
/**
 * Learn Java from https://www.liaoxuefeng.com/
 * 
 * @author liaoxuefeng
 */
public class Main {

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

}
/**
 * 定义抽象类Income
 */
abstract class Income {
	protected double income;
	// TODO
	public Income(double income) {
		this.income = income;
	}
	public abstract double getTax();
}
/**
 * 工资收入税率超过5000不超过10000是10%,超过10000的部分是20%
 */
class SalaryIncome extends Income {
	protected double salary;
	
	// TODO
	public SalaryIncome(double salary) {
		super(salary);
		this.salary = salary;
	}
	
	@Override
	public double getTax() {
		if(salary <= 5000) {
			return 0;
		}
		else if(salary > 5000 && salary <=10000) {
			return (salary - 5000) * 0.1;
		}
		else {
			return (salary-10000) * 0.2 + 5000 * 0.1;
		}
	}
}
/**
 * 稿费收入税率是20%
 */
class RoyaltyIncome extends Income{
	protected double royalty;
	// TODO
	public RoyaltyIncome(double royalty) {
		super(royalty);
		this.royalty = royalty;
	}
	@Override
	public double getTax() {
		return royalty*0.2;
	}
}

  • 1

Reply