一、背景
在jdk1.8中,接口中可以定义默认方法和静态方法,默认方法和静态要怎么使用呢?
二、使用
1.接口中静态方法的使用
接口中静态方法的使用可以直接通过接口名.方法名的形式进行调用。
代码:
public interface MyInterface1 {
static int test1(int a,int b){
return a+b;
}
static int test(int a,int b){
return a+b;
}
}
public class TestInterface {
public static void main(String[] args) {
MyInterface1.test1();
}
}
2.接口中默认方法的调用
接口中默认方法的调用需要通过实现类来调用
public class TestInterface implements MyInterface1 {
public static void main(String[] args) {
TestInterface testInterface = new TestInterface();
System.out.println(testInterface.test(1,2));
}
}
3.如果一个类,同时实现了两个接口,两个接口有相同的默认方法,那么需要重写这个默认方法
public interface MyInterface1 {
default int test(int a,int b){
return a+b;
}
}
default int test(int a,int b){
return a+b;
}
public class InterfaceTest implements MyInterface2,MyInterface1 {
@Override
public int test(int a, int b) {
return 0;
}
}