在数学中,函数就是有输入量、输出量的一套计算方案,也就是“拿数据做操作” 面向对象思想强调“必须通过对象的形式来做事情”
函数式思想则尽量忽略面向对象的复杂语法:“强调做什么,而不是以什么形式去做” 而我们要学习的Lambda表达式就是函数式思想的体现
//接口 interface Eatable { void eat(); } //实现类 class EatableImpl implements Eatable { @Override public void eat() { System.out.println("一天一苹果,医生远离我"); } } //测试类 public class test { public static void main(String[] args) { //在主方法中调用useEatable方法 Eatable e = new EatableImpl(); //父类引用指向子类对象 useEatable(e); //匿名内部类 useEatable(new Eatable() { @Override public void eat() { System.out.println("一天一苹果,医生远离我"); } }); //Lambda表达式 useEatable(()-> { System.out.println("一天一苹果,医生远离我"); }); } private static void useEatable(Eatable e) { e.eat(); } }
interface Flyable { void fly(String s); } public class test { public static void main(String[] args) { //在主方法中调用useFlyable方法 //匿名内部类 useFlyable(new Flyable() { @Override public void fly(String s) { System.out.println(s); System.out.println("飞机自驾游"); } }); System.out.println("‐‐‐‐‐‐‐‐"); //Lambda useFlyable((String s) -> { System.out.println(s); System.out.println("飞机自驾游"); }); } private static void useFlyable(Flyable f) { f.fly("风和日丽,晴空万里"); } }
interface Addable { int add(int x, int y); } public class test { public static void main(String[] args) { //在主方法中调用useAddable方法 useAddable((int x, int y) -> { return x + y; }); } private static void useAddable(Addable a) { int sum = a.add(10, 20); System.out.println(sum); } }
interface Addable { int add(int x, int y); } interface Flyable { void fly(String s); } public class test { public static void main(String[] args) { // useAddable((int x,int y) ‐> { // return x + y; // }); // 参数的类型可以省略 useAddable((x, y) -> { return x + y; }); //useFlyable((String s) ‐> { // System.out.println(s); // }); //如果参数有且仅有一个,那么小括号可以省略 // useFlyable(s ‐> { // System.out.println(s); // }); // 如果代码块的语句只有一条,可以省略大括号和分号 useFlyable(s -> System.out.println(s)); // 如果代码块的语句只有一条,可以省略大括号和分号,如果有return,return也要省略掉 useAddable((x, y) -> x + y); } private static void useFlyable(Flyable f) { f.fly("风和日丽,晴空万里"); } private static void useAddable(Addable a) { int sum = a.add(10, 20); System.out.println(sum); } }