Discuss / Java / 练习:用抽象类算税

练习:用抽象类算税

Topic source

YANGZY1202

#1 Created at ... [Delete] [Delete and Lock User]
// Main.java

public class Main {

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

}
// Income.java

/**
 * 定义接口Income
 */

public interface Income {

	double getTax();

}

// OtherIncome.java

public class OtherIncome implements Income {
	protected double income;
	
	public OtherIncome (double income) {
		this.income = income;
	}
	
	@Override
	public double getTax() {
	
		return income * 0.1;
	}

}

//SalaryIncome.java

public class SalaryIncome implements Income {
	protected double income;

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

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

}

//RoyaltyIncome.java
public class RoyaltyIncome implements Income {
	protected double income;
	
	public RoyaltyIncome(double income) {
		this.income = income;
	}
	
	@Override
	public double getTax() {
		return income * 0.2;
	}

}

YANGZY1202

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

为啥用接口算的数字(4200)和用多态继承算的数字(3200)不一样啊?

大家帮我哪儿出了点问题,下面是用继承算的:

//Main.java
public class Main {

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

}


//Income.java

public class Income {

	protected double income;

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

	public double getTax() {
		return income * 0.1; // 税率10%
	}

}

//SalaryIncome.java

public class SalaryIncome extends Income {

	public SalaryIncome(double income) {
		super(income);
	}

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


//RoyaltyIncome.java

public class RoyaltyIncome extends Income{

	public RoyaltyIncome(double income) {
		super(income);
	}

	@Override
	public double getTax() {
		
		return income * 0.2;  //稿费收入税率是20%
	}

}

SpiceGirll

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

你在用接口写的时候把工资收入的税率算法写错了

SalaryIncome那里的tax算错了,是(income - 5000) * 0.2, 不是income * 0.2。


  • 1

Reply