1 package com.test; 2 3 @FunctionalInterface 4 interface AddDo 5 { 6 int doAdd(int a, int b); 7 } 8 9 class Math10 {11 public AddDo addDo;12 13 public Math(AddDo addDo)14 {15 this.addDo = addDo;16 }17 18 public int add(int a, int b)19 {20 return this.addDo.doAdd(a, b);21 }22 }23 24 public class Java8LambdaTest25 {26 // 1. lambda表达式支持27 public static void lambdaSupport()28 {29 System.out.println("------ lambda表达式方式 ---------");30 Math math = new Math((a, b) ->31 {32 return a + b;33 });34 System.out.println(math.add(3, 5));35 36 System.out.println("------ 静态方法引用方式 ---------");37 Math math2 = new Math(Java8LambdaTest::staticHelper);38 System.out.println(math2.add(3, 5));39 40 System.out.println("------ 实例方法引用方式 ---------");41 Math math3 = new Math(new Java8LambdaTest()::instanceHelper);42 System.out.println(math3.add(3, 5));43 44 //构造方法引用方式为Java8LambdaTest::new45 }46 public static void main(String[] args)47 {48 lambdaSupport();49 }50 public static int staticHelper(int a, int b)51 {52 System.out.println("do staticHelper()");53 System.out.println("a: " + a + ", b: " + b);54 return a + b;55 }56 public int instanceHelper(int a, int b)57 {58 System.out.println("do helper()");59 System.out.println("a: " + a + ", b: " + b);60 return a + b;61 }62 }
2. 接口可以添加默认或者静态(两者只能存在一个修饰符)方法,但是接口仍然不能实例化,不能含有static代码块
1 package com.test; 2 3 interface MathOpt 4 { 5 default int add(int a, int b) 6 { 7 return a + b; 8 } 9 10 static int subtract(int a, int b)11 {12 return a - b;13 }14 }15 16 public class Java8InterfaceDefaultMethod17 {18 public static void main(String[] args)19 {20 System.out.println(MathOpt.subtract(3, 5));21 }22 }