Java 8 : 函数式接口例子

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 注解,来显示编译时错误。这个可选
例如:

@FunctionalInterface
public 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");
   }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值