java进阶 - Lambda表达式 - lambda和匿名类的区别35

package com.cyjt97.interior;

public class day04 {
    public static void main(String[] args) {
        use(new cs() {
            @Override
            public void show() {
                System.out.println("匿名类写法");
            }
        });
//        Lambda表达式,只允许操作函数式编程接口:有,且仅有一个抽象方法的接口
        use(()->{
            System.out.println("Lambda写法");
        });
    }

    public static void use(cs i){
        i.show();
    }
}
@FunctionalInterface
interface cs{
    void show();
}

  

 

package com.cyjt97.interior;

import java.util.Random;

public class day04 {
public static void main(String[] args) {
use(new cs() {
@Override
public void show(String msg) {
System.out.println("匿名类写法" + msg);
}
});
// Lambda表达式,只允许操作函数式编程接口:有,且仅有一个抽象方法的接口
use((String msg) -> {
System.out.println("Lambda写法" + msg);
});
// 如果 Lambda表达式的方法体代码只有一行代码可以省略大括号不写,同时要省略分号
use(msg -> System.out.println("Lambda省略写法写法" + msg));
// 如果这行代码是 return语句,必须省略 return不写,同时也必须省略";"不写
useRoomH(new RoomH() {
@Override
public int getRes() {
Random r = new Random();
int num = r.nextInt(100) + 1;
return num;
}
});
System.out.println("-----------------------------");
useRoomH(new RoomH() {
@Override
public int getRes() {
return new Random().nextInt(100)+1;
}
});
System.out.println("-----------------------------");
useRoomH(()->{return new Random().nextInt(100)+1;});
System.out.println("-----------------------------");
//相加数
useCale(new cale(){
@Override
public int calc(int a, int b) {
return a+b;
}
});
System.out.println("-----------------------------");
useCale(( a, b)->{ a-b});
}

public static void use(cs i) {
i.show("SB老板,不发工资");
}

private static void useRoomH(RoomH roomH) {
int res = roomH.getRes();
System.out.println(res);
}
private static void useCale(cale cale) {
int cal = cale.calc(10,20);
System.out.println(cal);
}
}
//String
@FunctionalInterface
interface cs {
void show(String msg);
}
//随机数
interface RoomH {
int getRes();
}
//相加数
interface cale{
int calc(int a,int b);
}

  

 

posted @ 2023-03-15 15:55  文采呱呱  阅读(16)  评论(0编辑  收藏  举报