在Java8之前的版本中,接口中只能声明常量和抽象方法,接口的实现类中必须实现接口中所有的抽象方法。而在Java8中,接口中可以声明 默认方法 和 静态方法。
Java 8中允许接口中包含具有具体实现的方法,该方法称为 “默认方法” ,默认方法使用 “ default ” 关键字修饰 。
示例:
public interface MyInterface {
default String getMsg(String srcMsg){
return "======"+srcMsg;
}
}
接口中的默认方法,有一个 “类优先” 原则:
若一个接口中定义了一个默认方法,而另外一个父类或接口中又定义了同一个同名的方法时:
示例1:
public interface MyInterface1 {
default String getMsg(String srcMsg){
return "===我是MyInterface1111111==="+srcMsg;
}
}
///////////////////////////////////////////////////////
public class MyClass1 {
public String getMsg(String srcMsg){
return "===我是MyClass11111==="+srcMsg;
}
}
///////////////////////////////////////////////////////
public class MySubClass1 extends MyClass1 implements MyInterface1 {
}
///////////////////////////////////////////////////////
public class InterfaceTest {
public static void main(String[] args) {
MySubClass1 ms1 = new MySubClass1();
String srcMsg = "Java 牛逼!!";
//MySubClass1 类继承了 MyClass1 类,实现了MyInterface1 接口,根据类优先原则,调用同名方法时,会忽略掉接口 MyInterface1 中的默认方法。
System.out.println(ms1.getMsg(srcMsg));//输出结果:===我是MyClass11111===Java 牛逼!!
}
}
示例2:
public interface MyInterface2 {
default String getMsg(String srcMsg){
return "===我是MyInterface2222222==="+srcMsg;
}
}
////////////////////////////////////////////////////////////////
public class MySubClass2 implements MyInterface1,MyInterface2 {
@Override
public String getMsg(String srcMsg) {
//同时实现了 MyInterface1,MyInterface2 接口,根据 类优先 原则,两个父接口中都提供了相同的方法,那么子类中就必须重写这个方法来解决冲突。
return MyInterface1.super.getMsg(srcMsg);
//return MyInterface2.super.getMsg(srcMsg);
//return "------"+srcMsg;
}
}
////////////////////////////////////////////////////////////////
public class InterfaceTest {
public static void main(String[] args) {
MySubClass2 ms2 = new MySubClass2();
//MySubClass2 重新实现了两个父接口中都存在的相同名称的方法。
System.out.println(ms2.getMsg(srcMsg));//输出结果:===我是MyInterface1111111===Java 牛逼!!
}
}
在Java8中,接口中允许添加 静态方法 ,使用方式: “接口名.方法名” 。
示例:
public interface MyInterface3 {
static String getMsg(String msg){
return "我是接口中的静态方法:"+msg;
}
static void main(String[] args) {
System.out.println(MyInterface3.getMsg("Java牛逼!!"));
}
}