Java接口的default关键字用法解释
// Main.java public class Main { public static void main(String[] args) { // TODO Income salary = new SalaryIncome(10000); Income royalty = new RoyaltyIncome(20000); double totalTax = salary.getTax() + royalty.getTax(); System.out.printf("总计缴税额是:%.2f", totalTax); } } // Income.java interface Income { default double getTax() { return 100.02; }; } // SalaryIncom.java public class SalaryIncome implements Income{ protected double income; // 构造方法 public SalaryIncome(double income) { this.income = income; } } // 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; } } /*对于default我的理解是,正常不使用default定义方法的话,继承该interface的子类都必须重写所有的抽象方法,但是如果在interface中通过default定义了一个方法,那么这个方法不是子类所必须重写的。 */