jdk1.8以前,只允许在接口中定义两种类型的数据: 全局静态变量和抽象方法。但在jdk1.8中引入了两个全新的概念:
-
在接口中可以使用default关键字修饰非抽象方法。
-
接口内可以编写静态方法,并且可以被实现。
全局静态变量:
public interface MyInterface {
//public static Integer age = 1;
//public static String name = "name";
Integer age = 1;
String name = "name";
}
抽象方法:
abstract String get36D();
String get36D(String name);
加不加abstract 都一样,并且方法可以重写
**
默认方法:
在接口中可以使用default关键字修饰非抽象方法。
**
public interface MyInterface1 {
default String getName(){
return "嘿嘿嘿";
}
}
public interface MyInterface2 {
default String getName(){
return "呵呵呵";
}
}
public class MyClass {
public String getName(){
return "桀桀桀";
}
}
定义两个接口一个类,同样有getName()方法;
继承实现类和接口
public class SubClass extends MyClass implements MyInterface1{
}
编写测试类:
public class Test{
@Test
public void test1(){
SubClass subClass = new SubClass();
System.out.println( subClass.getName());
}
}
执行结果:
桀桀桀
这是MyClass类中打印的,说明执行了类中的方法,而没有执行接口中的方法
修改SubClass类:
取消继承,实现两个接口
public class
SubClassimplements MyInterface1,MyInterface2{
}
发现SubClass报错了,提示是MyInterface1和MyInterface2中都有getName()方法,SubClass不知道要实现那个,要你手动指定:
public class SubClass implements MyInterface1,MyInterface2{
@Override
public String getName() {
return MyInterface2.super.getName();
}
}
再次执行测试类:
执行结果:
呵呵呵
这是MyInterface2接口中定义的默认方法打印出来的,说明执行的是MyInterface2中的getName()方法
静态方法:
必须要加static关键字,并且可以重写和传递参数的
public interface MyInterface1 {
static void show(){
System.out.println("123123");
}
static String show(String str){
return str;
}
}
编写测试方法:
@Test
public void test2(){
MyInterface1.show();
String qaeqaaqaraqctrl5 = MyInterface1.show("qaeqaaqaraqctrl5");
System.out.println(qaeqaaqaraqctrl5);
}
执行结果:
123123
qaeqaaqaraqctrl5
md 感觉换了一门语言,淦!!!