Java8新特性——接口的默认方法和类方法

时间:2022-06-01 19:37:51

Java8新增了接口的默认方法和类方法:

以前,接口里的方法要求全部是抽象方法,java8以后允许在接口里定义默认方法和类方法:

不同的是:

默认方法可以通过实现接口的类实例化的对象来调用,而类方法只能在本接口中调用或在实现类中实现

下面是使用实例:

 public interface MyInter {
default void df(){ //声明一个接口的默认方法 System.out.println("i'am default f");
sf(); //调用本接口的类方法
}
static void sf(){ //声明一个接口的类方法 System.out.println("i'am static f");
}
}
 public class Man implements MyInter{    //Man类实现MyInter接口
}
 public class Test extends Man{

     public static void main(String[] args) {
Man man=new Man();
man.df(); //通过man对象调用MyInter接口的默认方法df()
} }