标准格式:
三要素:形式参数 箭头 代码块
格式:(形式参数)->{代码块}
形式参数:如果多个参数用逗号隔开,无参留空
->:英文中划线和大于号组成
代码块:具体要做的事
使用前提:
有一个接口
接口中有且仅有一个抽象方法
public interface Eatable { void eat(); }
public class EatableImpl implements Eatable{ @Override public void eat() { System.out.println("一天一苹果"); } }
public class EatableDemo { 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(); } }
public interface Eatable { void eat(String name); } public class EatDemo { public static void main(String[] args) { useEat((String name) -> { System.out.println(name); System.out.println("输出的啥"); }); } private static void useEat(Eatable e){ e.eat("苹果"); } }
public interface Addable { int add(int x,int y); } 1. 2. 3. public class AddableDemo { public static void main(String[] args) { useAddable( (int x,int y ) -> { return x+y; }); } private static void useAddable(Addable a){ int sum = a.add(5, 7); System.out.println(sum); } }