Java

137. 함수형 인터페이스 - 패스트캠퍼스 백엔드 부트캠프 3기

gkss2tpt 2025. 1. 8. 18:18

1. 함수형 인터페이스

  • 단 하나의 추상 메서드만 선언된 인터페이스
interface MyFunction {	// 함수형 인터페이스
    public abstract int max(int a, int b);
}

MyFunction f = new MyFunction() {
    public int max(int a, int b) {
        return a > b ? a : b ;
    }
};

int value = f.max(3,5);	// OK. MyFunction에 max가 있음
@FunctionalInterface	// 함수형 인터페이스인지 체크
interface MyFunction {
    public abstract int max(int a, int b);
}
public class Ex02_01 {
    public static void main(String[] args) {
        MyFunction f = new MyFunction() {	// 익명 클래스
            @Override
            public int max(int a, int b) {
                return a > b ? a : b;
            }
        };

        int v = f.max(3,5);

        System.out.println(v);
    }
}
  • 함수형 인터페이스 타입의 참조변수로 람다식을 참조할 수 있음.
@FunctionalInterface	// 함수형 인터페이스는 단 하나의 추상 메서드만 가져야 함.
interface MyFunction {
    public abstract int max(int a, int b);
}
public class Ex02_01 {
    public static void main(String[] args) {
    	
        // 람다식(익명 객체)을 다루기 위한 참조변수의 타입은 함수형 인터페이스로 한다.
        MyFunction f = (a, b) -> a > b ? a : b;

        int v = f.max(3,5);	// 함수형 인터페이스

        System.out.println(v);
    }
}

 

2. 함수형 인터페이스 타입의 매개변수, 반환타입

  • 함수형 인터페이스 타입의 매개변수
void aMethod(MyFunction f) {	// 매개변수로 람다식을 받겠다는 뜻
    f.myMethod();	// MyFucntion에 정의된 메서드 호출 -> 람다식 호출
}

@FunctionalInterface
interface MyFunction {
    void myMethod();
}

// 1
MyFunction f = () -> System.out.println("myMethod()");
aMethod(f);

// 2
aMethod(() -> System.out.println("myMethod()"));
  • 함수형 인터페이스 타입의 반환타입
MyFunction myMethod() {
    MyFunction f = () -> {};
    return f;	// 람다식반환
}

MyFunction myMethod() {
    return () -> {}; // 람다식
}

 

3. 예제

@FunctionalInterface
interface MyFunction {
    void run();  // public abstract void run();
}

public class Ex02_02 {
    static void execute(MyFunction f) { // 매개변수의 타입이 MyFunction인 메서드
        f.run();
    }

    static MyFunction getMyFunction() { // 반환 타입이 MyFunction인 메서드
        MyFunction f = () -> System.out.println("f3.run()");
        return f;
    }
    public static void main(String[] args) {
        // 람다식으로 MyFunction의 run()을 구현
        MyFunction f1 = () -> System.out.println("f1.run()");

        MyFunction f2 = new MyFunction() {
            @Override
            public void run() {
                System.out.println("f2.run()");
            }
        };

        MyFunction f3 = getMyFunction();

        f1.run();
        f2.run();
        f3.run();

        execute(f1);
        execute( () -> System.out.println("run()") );
    }
}