在Java8之前,接口中方法只能为抽象的。在Java8中,除了定义抽象方法,还可以为接口添加静态方法和默认方法。从技术角度来说,这是完全合法的,只是他看起来违反了一个抽象定义的概念。
(有一说一,我想到之前在学习C#时学习到的虚方法,它不仅可以定义方法体,继承他的子类也可以重写该虚方法,但是Java中不需要定义虚方法也可以直接重写父类的方法。Java~ 永远滴神~
至于什么是接口中的静态方法和默认方法,我在下面演示一下
interface Java8Interface{
//静态方法
public static void method1(){
System.out.println("我是method1");
}
//默认方法
public default void method2(){
System.out.println("我是method2");
}
//默认方法2
default void method3(){
System.out.println("我是method3");
}
}
静态方法:使用static关键字修饰。可以通过接口直接调用静态方法,并执行其方法体。我们经常在相互一起使用的类中使用静态方法。你可以在标准库中找到像Collection/Collections或者Path/Paths这样成对的接口类
(Collections是Collection的工具类,通过Collections类对Collection接口进行操作,如果接口中存在静态方法使自己可以对自己进行操作,那么Collections类则可以被替代
默认方法:使用default关键词修饰,可以通过实现类的对象来调用。我们在已有的接口中提供新方法的同时,还保持了与旧版本代码的兼容性。
比如:Java 8 API中对Collection、List、Comparator等接口提供了丰富的默认方法
1.接口中定义的静态方法,只能通过接口来调用
class SubClassTest{
public static void main(String[] args) {
SubClass sC1 = new SubClass();
//1.1.接口中定义的静态方法,只能通过接口来调用
sC1.method1(); //Static method may be invoked on containing interface class only
SubClass.method1();//Static method may be invoked on containing interface class only
Java8Interface.method1(); //可以执行
}
}
class SubClass implements Java8Interface{
}
2.通过实现类的对象 可以调用接口中的默认方法
class SubClassTest{
public static void main(String[] args) {
SubClass sC1 = new SubClass();
//2.通过实现类的对象 可以调用接口中的默认方法
sC1.method2(); //可以执行
sC1.method3(); //可以执行
}
}
3.如果实现类重写了接口中的默认方法,调用时,仍然调用的时重写以后的方法
class SubClassTest{
public static void main(String[] args) {
SubClass sC1 = new SubClass();
//2.通过实现类的对象 可以调用接口中的默认方法
//3.如果实现类重写了接口中的默认方法,调用时,仍然调用的时重写以后的方法
sC1.method2(); //可以执行
sC1.method3(); //我重写了method3
}
}
class SubClass implements Java8Interface{
public void method3(){
System.out.println("我重写了method3");
}
}