java: incompatible types: ch14.MyFunction is not a functional interface
multiple non-overriding abstract methods found in interface ch14.MyFunction
@FunctionalInterface
interface MyFunction {
void method1();
void method2(); // 두 개의 추상 메서드 → 오류 발생
}
함수형 인터페이스는 추상 메서드가 반드시 하나만 존재해야 하며, 이 조건을 위반하면 컴파일러가 발생한다.
예시 (정상):
@FunctionalInterface
interface MyFunction {
void method1(); // 추상 메서드 하나만 존재
default void method2() { } // default 메서드는 허용
}
예시 (에러발생)
interface MyFunction {
public abstract int max(int a, int b);
public int min(int a, int b) { // 에러 발생
return Math.min(a,b);
}
}
위 코드에서 public int min(int a, int b) { ... }가 안 되는 이유는,
인터페이스에서 구현(몸체)이 있는 메서드는 반드시 default 또는 static 키워드를 사용해야 하기 때문입니다. 왜? 그냥 자바 규칙이다.
int max(int a, int b);default int min(int a, int b) { ... }static int util(int a) { ... }public int min(...) { ... }는 안 되는가?default 또는 static 키워드를 붙이면 구현이 있는 메서드를 인터페이스에 선언할 수 있습니다.인터페이스에서 구현부가 있는 메서드는 반드시 default 또는 static으로 선언해야 합니다.
interface MyFunction {
int max(int a, int b); // 추상 메서드
default int min(int a, int b) { // default 메서드
return Math.min(a, b);
}
}