public class imsi2 {
public static void main(String[] args) {
MyFunction21 f = new MyFunction21() {
@Override
public int max(int a, int b) {
return a > b ? a : b;
}
};
int value = f.max(3, 5);
System.out.println("value="+value);
}
}
@FunctionalInterface // 함수형 인터페이스는 단 하나의 추상 메서드만 가짐
interface MyFunction21 {
public abstract int max(int a, int b);
}
위 코드를 함수형 인터페이스로 아래와 같이 간단하게 작성 가능
public class imsi2 {
public static void main(String[] args) {
// 람다식을 다루기 위한 참조변수의 타입은 함수형 인터페이스로 함
MyFunction21 f = (a, b) -> a > b ? a : b; // 람다식 (익명객체)
int value = f.max(3, 5);
System.out.println("value="+value);
}
}
@FunctionalInterface // 함수형 인터페이스는 단 하나의 추상 메서드만 가짐
interface MyFunction21 {
public abstract int max(int a, int b);
}
람다식은 메서드인데 이름이 없음 그래서 메서드를 사용하기 위해 함수형 인터페이스의 추상메서드에서 이름(max)을 지정해줌
void aMethod(MyFunction f) {
f.myMethod(); // MyFunction에 정의된 메서드(람다식) 호출
}
MyFunction f = () -> System.out.println("myMethod()");
aMethod(f);
// aMethod(() -> System.out.prinln("myMethod()"));
MyFunction myMethod() {
MyFunction f = () -> ();
return f;
}
// MyFunction myMethod() {
return () -> {};
}
package ch14;
@FunctionalInterface
interface MyFunction11 {
void run(); // public abstract void run();
}
public class imsi3 {
static void execute(MyFunction11 f) { // 매개변수 타입이 MyFuncion11인 메서드
f.run();
}
public static void main(String[] args) {
// 람다식으로 MyFunction의 run()을 구현
MyFunction11 f1 = () -> System.out.println("f1.run()");
MyFunction11 f2 = new MyFunction11() {
@Override
public void run() {
System.out.println("f2.run()");
}
};
MyFunction11 f3 = () -> System.out.println("f3.run()");
f1.run();
f2.run();
f3.run();
execute(() -> System.out.println("f1.run()"));
execute( () -> System.out.println("run()"));
}
}