方法引用
方法引用的要求
- 参数类型一致 (并不是必须没有参数!)
- 返回值类型一致
- 对象调用静态方法,没有方法引用的改写
方法引用的几种方式
- 类名::new
- 类名::静态方法名
- 引用名(对象名)::实例方法名
- 类名::实例方法名
代码示例
public class No05 {
public static void main(String[] args) {
F1 f1 = new F1() {
@Override
public String test(String a) {
return new String(a);
}
};
F1 f11 = (str) -> new String(str);
F1 f12 = String::new;
F2 f2 = new F2() {
@Override
public int test(int a, int b) {
return Integer.sum(a, b);
}
};
F2 f21 = (a, b) -> Integer.sum(a, b);
F2 f22 = Integer::sum;
T1 t1 = new T1();
F3 f3 = new F3() {
@Override
public void test(int a, int b) {
t1.test(a, b);
}
};
F3 f31 = (a, b) -> t1.test(a, b);
F3 f32 = t1::test;
F4 f4 = new F4() {
@Override
public void test(String a) {
a.toUpperCase();
}
};
F4 f41 = (str) -> str.toUpperCase();
F4 f42 = String::toUpperCase;
}
}
interface F1 {
String test(String a);
}
interface F2 {
int test(int a, int b );
}
interface F3 {
void test(int a, int b);
}
interface F4 {
void test(String a);
}
class T1{
public void test(int a, int b) {
System.out.println(a+b);
}
}