默认方法和静态方法
- JDK8 以后接口可以有方法体。
- 默认方法 default :
- 可以通过实现接口的类实例化的对象来调用,也可以被重写。
- 是Public的。
- 静态方法 static :
- 只能在本接口中调用,职责上是工具方法。
- 默认方法 default :
public interface In {
int get();
static int getStatic() {
return 1;
}
default int getDefault() {
getStatic();
return 1;
}
}
对比抽象类
- 这是接口向抽象类的靠近。
- 抽象类可做,接口不可做:
- 抽象类能够定义 非static final 的属性,而接口的属性都是static final的。
- 抽象类能够定义 非public 方法,而接口的方法都是public的。
- 接口可做,抽象类不可做:
- 接口可以多继承(实现),而抽象类只能单继承。