/**
* Lambda表达式的简化
* 1.去掉所有参数类型
* 2.去掉圆括号"()",花括号"{}"和分号";"
*/
public class DemoLambda3 {
public static void main(String[] args) {
// 匿名内部类
Human human = new Human() {
@Override
public void getAge(int age) {
System.out.println("I'm " + age + " years old.");
}
};
Color color = new Color() {
@Override
public void getColor(int r, int g, int b) {
System.out.println("I'm rgb(" + r + ", " + g + ", " + b + ")");
}
};
human.getAge(18);
color.getColor(1, 2, 3);
// Lambda表达式
human = (int age) -> {
System.out.println("I'm " + age + " years old.");
};
color = (int r, int g, int b) -> {
System.out.println("I'm rgb(" + r + ", " + g + ", " + b + ")");
};
human.getAge(3);
color.getColor(10, 20, 30);
/*
Lambda表达式简化
1.去掉所有参数类型
注意: 参数类型要么都保留,要么都去掉.
*/
human = (age) -> {
System.out.println("I'm " + age + " years old.");
};
color = (r, /*int*/ g, b) -> {
System.out.println("I'm rgb(" + r + ", " + g + ", " + b + ")");
};
human.getAge(100);
color.getColor(0, 0, 0);
/*
Lambda表达式简化
2.去掉圆括号"()",花括号"{}"和分号";"
注意:
只有一个参数时, 才可以去掉圆括号"()"
方法体内只有一条语句时, 才可以去掉花括号"{}"和分号";"
*/
human = age -> System.out.println("I'm " + age + " years old.");
color = (r, g, b) -> {
System.out.println("I'm rgb(" + r + ", " + g + ", " + b + ")");
System.out.println("In other words, I am white.");
};
human.getAge(100);
color.getColor(0, 0, 0);
}
}
/**
* 函数式接口
* 抽象方法有1个参数
*/
interface Human {
void getAge(int age);
}
/**
* 函数式接口
* 抽象方法有3个参数
*/
interface Color {
void getColor(int r, int g, int b);
}