- Interface是java实现abstraction和multiple inheritances的一种机制
- Java interface包括static constants和abstract methods (Java8之后,interface还可以包含default方法和static方法,Java9之后加入了private方法)
- all variables in an interface are by default
public static final(constant)
- all methods in an interface are by default
public abstract(除了default方法和static方法)
- a class that implement an interface must implements all the abstract methods declared in the interface
- inside an interface, constructor is not allowed, since interface cannot be instantiated
- static方法不能被子类inherit,只能通过接口名.方法名调用
public interface Payment {
double TRANSACTION_FEE = 2.5;
void pay(double amount);
default void printReceipt(double amount) {
System.out.println("Transaction Fee: $" + calculateFee(amount));
}
static void showAvailablePaymentMethods() {
System.out.println("Available payment methods: Credit Card, PayPal, Alipay");
}
private double calculateFee(double amount) {
return amount * TRANSACTION_FEE / 100;
}
}