和ES6的箭头函数类似,是想把方法作为参数进行传递
- 匿名类: 直接new一个借口,然后在后面跟上实现代码
```java interface Polygon { public void display(); }object1 = new type(parameterList){
//匿名类代码
}
class AnonymousDemo { public void createClass() {
// 匿名类实现一个接口
Polygon p1 = new Polygon() {
public void display() {
System.out.println("在匿名类内部。");
}
};
p1.display();
} }
2. lambda
```java
private static void filter(List<Hero> heros,HeroChecker checker) {
for (Hero hero : heros) {
if(checker.test(hero))
System.out.print(hero);
}
}
//在别处
filter(heros,h->h.hp>100 && h.damage<50);
Java 中的 Lambda 表达式通常使用 (argument) -> (body)
语法书写,例如:
(arg1, arg2...) -> { body }
(type1 arg1, type2 arg2...) -> { body }
以下是一些 Lambda 表达式的例子:
(int a, int b) -> { return a + b; }
() -> System.out.println("Hello World");
(String s) -> { System.out.println(s); }
() -> 42
() -> { return 3.1415 };
然后函数式接口是只有一个抽象方法声明的接口,可以用 lambda
给抽象方法接口赋值
简单地写了个例子
import java.io.*;
public class Test {
interface test{
public void hh(int a, int b);
}
public static void main(String[] args) {
getTest((a, b) -> { System.out.println(a + b); });
}
public static void getTest(test tt){
tt.hh(1, 2);
}
}