Java接口新特性

来源:互联网 发布:广东人吃福建人 知乎 编辑:程序博客网 时间:2024/06/06 03:26

1、在接口中,可以直接添加静态方法。

该静态方法作为接口的类方法,可以直接使用。不需要依托某个实现类。

2、在接口中,可以直接添加非抽象的实例方法。

在实例方法的申明中,需要增加default关键字修饰,因此这种方法也称为默认方法。他是接口自带的方法。接口被实现后,实例可以直接使用这些默认方法,同时如果对默认方法需要重写时,可以直接重写即可。

这两点新特性相对于java8之前的版本来说,可以说有质的改变。

public interface SourceInterface  2 { 3     int a = 5; 4     int b = 10; 5  6     public static int add()  7     { 8         return a + b; 9     }10 11     public static void reset() 12     {13         // do sth14     }15 16     public default int f1()17     {18         return a;19     }20 21     public default void f2()22     {23         // do sth24     }25 }26 27 class learnCode28 {29     public void userInterface()30     {31         int xx = SourceLearning.add();32         SourceLearning.reset();33         SourceLearning instance = new SourceLearning()34         {35             @Override36             public void f2()37             {38                 // do sth 、39             }40         };41         instance.f1();42         instance.f2();43         //int y=instance.add(); 注意这句会编译错误44     }45 }

原创粉丝点击