上善若水 厚德载物

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

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

例如:

Thread t =new Thread(new Runnable(){ (){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();}FunctionInterfaceTestImpl {(String[] args){//老方式用匿名内部类FunctionalInterfaceTest fit = new FunctionalInterfaceTest(){(){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..!”); }}{ (){System.out.println(“show method”); } (String[] args){DefaultInterfaceTest obj = new DefaultInterfaceTestImpl();obj.show();//输出: show methodobj.display();//输出 : Default method from interface can have body..!}}

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

多重实现

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

{ default void show(){System.out.println(“show from Test”); }}{default void show(){System.out.println(“show from Test”); }} Test, AnotherTest{//这里的show()方法有继承歧义}

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

Test, AnotherTest{void show(){System.out.println(“Main show method”); }}

有的旅行是为了拓宽眼界,浏览风景名胜。

上善若水 厚德载物

相关文章:

你感兴趣的文章:

标签云: