Java 8 : 函数式接口例子

来源:互联网 发布:路径依赖的案例数据 编辑:程序博客网 时间:2024/05/22 17:29

Java 8为了支持lambda 表达式而引入了函数式接口。只有一个抽象方法的接口就能被当作函数式接口调用。

Runnable,Comparator,Coneable 都是一些函数式接口的例子。我们能Lambda表达式来实现这些函数式接口。

例如:

Thread t =new Thread(new Runnable(){   public void run(){     System.out.println("Runnable implemented by using Lambda Expression");   }});

这是未引入lambda之前建线程的方式。

Runnabl只有一个抽象方法,我们可以把它当做一个函数式接口。我们像下面这样使用Lambda表达式:

Thread t = new Thread(()->{   System.out.println("Runnable implemented by using Lambda Expression");});

这里我们只传lambda表达式而不是Runnable对象。

声明我们自己的函数式接口

我们可以在一个接口里定义一个单独的抽象方法来声明我们自己的函数式接口。

public interface FunctionalInterfaceTest{void display();}//实现上面接口的测试类public class FunctionInterfaceTestImpl {      public static void main(String[] args){     //老方式用匿名内部类     FunctionalInterfaceTest fit = new FunctionalInterfaceTest(){        public void display(){           System.out.println("Display from old way");        }};     fit.display();//outputs: Display from old way     //用lambda表达式     FunctionalInterfaceTest newWay = () -> {System.out.println("Display from new Lambda Expression");}        newWay.display();//outputs : Display from new Lambda Expression     }}

我们可以加上@FunctionalInterface 注解,来显示编译时错误。这个可选
例如:

@FunctionalInterfacepublic interface FunctionalInterfaceTest{   void display();   void anotherDisplay();//报错, FunctionalInterface应该只有一个抽象方法}

默认方法

函数式接口只能有一个抽象方法但可以有多个默认方法。

默认方法在Java 8中引入的,为接口添加了新方法而不会影响实现类。

interface DefaultInterfaceTest{  void show();  default void display(){     System.out.println("Default method from interface can have body..!");  }}public class DefaultInterfaceTestImpl implements DefaultInterfaceTest{   public void show(){         System.out.println("show method");   }   //我们不需要实现默认方法   public static void main(String[] args){          DefaultInterfaceTest obj = new DefaultInterfaceTestImpl();          obj.show();//输出: show method          obj.display();//输出 : Default method from interface can have body..!        }}

默认方法的主要用途是没有强制实现类,我们能给接口添加一个方法(非抽象)。

多重实现

如果相同的默认方法出现在两个接口里,而一个类实现了这两个接口,这里就会抛出一个错误。

//带show()方法的普通接口interface Test{  default void show(){     System.out.println("show from Test");  }}//有相同show()方法的另一接口interface AnotherTest{   default void show(){      System.out.println("show from Test");   }}//Main类实现两个接口class Main implements Test, AnotherTest{//这里的show()方法有继承歧义}

这个类不能编译因为Test,AnotherTest接口的show()方法有歧义,为了解决这个问题我们需要在Main类里面来重写show()方法。

class Main implements Test, AnotherTest{   void show(){      System.out.println("Main show method");   }}
0 0