default & static 需要方法体
default
在接口中,增加default方法, 是为了既有的成千上万的Java类库的类增加新的功能, 且不必对这些类重新进行设计。
比如, 只需在接口中增加default void print(), 它们的实现类默认实现此方法, 不必为每个子类都重新实现这个方法。
public interface InterfaceA {
default void print() {
System.out.println("interface A - print()");
};
}
public class InterfaceImpl implements InterfaceA {
}
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
new InterfaceImpl().print();
}
}
也可以重写default方法,当实现多个接口,而其中含有相同的default方法名时,实现类需要重新default方法
static
与普通static方法一样
public interface InterfaceA {
static void calculate() {
System.out.println("interface A - calculate()");
}
}
public class InterfaceImpl implements InterfaceA {
}
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
InterfaceA.calculate();
}
}