Java 8 新特性

226 阅读1分钟
  1. Java 8 允许我们给接口添加一个非抽象的方法实现,只需要使用default关键字即可,这个特征又叫扩展方法。
public interface Vehicle {
   default void print(){
      System.out.println("我是一辆车!");
   }
}
  1. Lambda 表达式。参数 => 主体。Lambda表达返回右边表达式的结果。
// 1. 不需要参数,返回值为 5  
() -> 5  
  
// 2. 接收一个参数(数字类型),返回其2倍的值  
x -> 2 * x  
  
// 3. 接受2个参数(数字),并返回他们的差值  
(x, y) -> x – y  
  
// 4. 接收2个int型整数,返回他们的和  
(int x, int y) -> x + y  
  
// 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)  
(String s) -> System.out.print(s)
  1. 用 :: 关键字来传递方法和构造函数。

  2. 函数式接口。

如定义了一个函数式接口如下:

@FunctionalInterface
interface GreetingService 
{
    void sayMessage(String message);
}

那么就可以使用Lambda表达式来表示该接口的一个实现(注:JAVA 8 之前一般是用匿名类实现的):

GreetingService greetService1 = message -> System.out.println("Hello " + message);

转自JDK1.8新特性 my.oschina.net/134596/blog…