FunctionalInterface 는 생성자로 생성할수 있다?

서버란·2024년 8월 31일

자바 궁금증

목록 보기
10/35
  • FunctionalInterface 자체는 생성자를 직접 생성할 수는 없습니다.
  • FunctionalInterface는 단 하나의 추상 메서드를 가지는 인터페이스로, 함수형 프로그래밍의 특성을 지원합니다.
  • 실제로 객체를 생성하는 것은 FunctionalInterface의 구현체나 람다 표현식, 메서드 참조 등을 통해 이루어집니다.

FunctionalInterface와 생성자의 관계

  1. FunctionalInterface는 객체를 직접 생성하지 않음:
    • FunctionalInterface는 단지 인터페이스이며, 직접 객체를 생성할 수 없습니다.
    • 객체를 생성하려면 이 인터페이스를 구현하는 클래스가 필요하거나, 람다 표현식 또는 메서드 참조를 사용할 수 있습니다.
  2. 람다 표현식과 메서드 참조:
  • 람다 표현식이나 메서드 참조는 FunctionalInterface를 구현하는 익명 객체를 생성합니다.
  • 이러한 방식은 FunctionalInterface를 인스턴스화하여 사용할 수 있게 해줍니다.

예제

1. 람다 표현식으로 객체 생성

  • 람다 표현식은 FunctionalInterface를 구현하는 익명 클래스를 간결하게 작성할 수 있는 방법입니다.
@FunctionalInterface
public interface BinaryOp {
    int apply(int a, int b);
}

public class Main {
    public static void main(String[] args) {
        BinaryOp add = (x, y) -> x + y;
        System.out.println(add.apply(1, 2)); // 출력: 3
    }
}

2. 메서드 참조로 객체 생성

  • 메서드 참조는 기존 메서드를 FunctionalInterface의 구현으로 사용합니다.
@FunctionalInterface
public interface BinaryOp {
    int apply(int a, int b);
}

public class Something {
    public static int add(int i, int j) {
        return i + j;
    }
}

public class Main {
    public static void main(String[] args) {
        BinaryOp op = Something::add;
        System.out.println(op.apply(1, 2)); // 출력: 3
    }
}

3. 익명 클래스로 객체 생성

  • 익명 클래스를 사용하여 FunctionalInterface를 구현하는 방법입니다.
@FunctionalInterface
public interface BinaryOp {
    int apply(int a, int b);
}

public class Main {
    public static void main(String[] args) {
        BinaryOp op = new BinaryOp() {
            @Override
            public int apply(int a, int b) {
                return a + b;
            }
        };
        System.out.println(op.apply(1, 2)); // 출력: 3
    }
}

요약

  • FunctionalInterface 자체는 객체를 생성하지 않습니다.
  • 람다 표현식, 메서드 참조, 익명 클래스 등을 통해 FunctionalInterface의 구현체를 생성할 수 있습니다.
  • FunctionalInterface는 단 하나의 추상 메서드를 가지며, 이 메서드를 람다 표현식이나 메서드 참조를 통해 구현합니다.

따라서 FunctionalInterface를 직접 생성하는 것이 아니라, 이 인터페이스를 구현하는 방법으로 객체를 생성하고 사용할 수 있습니다.

profile
백엔드에서 서버엔지니어가 된 사람

0개의 댓글