Java 함수형 인터페이스

murkgom·2022년 7월 6일
0

@FunctionalInterface

함수형 인터페이스
추상 메서드가 오직 하나만 존재하는 인터페이스

Java의 기본 Functional Interface

base

  • Predict : boolean test(T t)
  • Consumer : void accept(T t)
  • Supplier : T get()
  • Function<T,R> : R apply(T t)
  • Comparator : int compare(T o1, T o2)
  • Runnable : void run()

Bi(파라미터가 1 + 1개)

  • BiPredict : boolean test(T t, U u)
    ...

기본형(not 제네릭 함수형)

  • IntPredicate : boolean test(int a)
    ...
  • IntToDoubleFunction : double apply(int a)
    ...
  • IntFunction : R apply(int a)
    ...
  • ToIntFunction : int apply(T t)
    ...

익명 객체

잠깐 쓰고 말 클래스(or 인터페이스)의 객체.

기본 컨셉

부모 클래스의 상속 or 인터페이스의 구현

interface SampleInterface {
  	String getName();
}
  
class Parent implements SampleInterface {
  	@Override
  	public String getName() {
	  	return "parent";
  	}
}
  
public static void main(String[] args) {
  	//부모 클래스 객체 생성
	SampleInterface parentClassInstance = new Parent();
  	//부모 클래스를 상속받는 익명 클래스의 객체 생성
	SampleInterface anonymousClassInstance = new Parent() {
		@Override
		public String getName() {
			return "anonymous";
		}
	};
  	//람다를 이용한 객체 생성
  	//SampleInterface에 추상 메서드가 오직 하나이기 때문에 알아서 추론
	SampleInterface lambdaInstance = () -> "lambda!";

	System.out.println(parentClassInstance.getName());		//parent
  	System.out.println(anonymousClassInstance.getName());	//anonymous
	System.out.println(lambdaInstance.getName());			//lambda!
}

0개의 댓글