Discuss / Java / 第三行incomes数组第一个数据 new Income(3000)报错啥情况 No enclosing instance of type Main is accessible. Must qu

第三行incomes数组第一个数据 new Income(3000)报错啥情况 No enclosing instance of type Main is accessible. Must qu

Topic source
public class Main {
	public static void main(String[] args) {
		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);
	}
	
	public class Income {

		protected double income;

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

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

	}

	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;
		}
	}

	public class RoyaltyIncome extends Income{
		public RoyaltyIncome(double income) {
			super(income);
		}
		@Override
		public double getTax() {
			return this.income * 0.2; 
		}
	}

}

廖雪峰

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

正常情况不要把class定义在另一个class里面,这叫inner class,和普通class不一样

谢谢廖老师的回复!我已经明白了,应该放在类外面,是四个独立的类,而且一个java程序中只能有一个public class,应该把后面三个public去掉。


  • 1

Reply