新特性
在以往无知的经验中, 抽象类与接口有着较大的区别, 例如可以在抽象类中撰写函数实现但在接口中不行
可这一切在Java8中有了变化, 接口default和static关键字的加入改变了这一不同
示例
在新的接口中, 我们可以这样定义:
public interface IPerson {
static String getName() {
return "person";
}
default Integer getSex() {
return 1;
}
String getAddress();
}
public class Person implements IPerson {
@Override
public String getAddress() {
return null;
}
}
其中的getName和getSex可以直接在接口级别进行调用:
public class Test {
public void test() {
IPerson.getName();
new Person().getSex();
}
}
注意
虽然接口可以写方法了, 但他和抽象类还是有本质不同的:
| 功能 | 抽象类 | 接口 |
|---|---|---|
| 方法实现 | √ | √(但无法覆写equals/hashCode/toString) |
| 多继承 | × | √ |
| 变量 | 全部 | 只能声明static和final变量 |