17-Functional Interface



Functional Interface

  • 람다식 인터페이스는 하나의 메소드만 있고, 이에 따라서 자바는 인터페이스 표준을 제공.
  • 람다식을 위한 Functional Interface. 리턴값은 없고, 메소드는 단 하나만 사용한다.
    • 메소드를 여러 개 사용시, 변수값을 제거해 식을 최소화한 람다식에서 충돌이 일어날 수 있기 때문
@FunctionalInterface
interface I1{
  void m1(); // 매개변수 없고 리턴값 없는 람다식
}
@FunctionalInterface
interface I2{
  void m2(int i); // 매개변수 int 1개, 리턴값 int 람다식
}
@FunctionalInterface
interface I3{
  void m2(int i); // 매개변수 int 1개, 리턴값 int 람다식
}
  • 이러한 표준 API의 (한 개의 추상 메소드를 갖는)함수적 인터페이스는 모두 람다식을 이용해 익명 구현 객체로 표현이 가능하다.
//api 라이브러리 인터페이스 
interface Consumer{
  void accept(Object); // 매개변수 모든 객체 가능, 1개. 리턴값x 의 경우 구현해서 사용
}
Comsumer c = o -> (o.toString()...);
c.accept(new Employee());


interface Supplier{
  Object get(); // 매개변수가 없고 리턴값은 있다 
}

Supplier s = () -> {o.toString() ... return o}


  • Functional Interface와 람다식
package day8;
@FunctionalInterface
interface Math{
	public int calc(int first, int second);
	//public double calc2(double f, double s);  > 람다식에 인터페이스는 하나만 허용.
}
@FunctionalInterface
interface C{
	public int calc(int first, int second);
}
@FunctionalInterface
interface A{
	int ma();
}
@FunctionalInterface
interface B{
	int mb(int i);
}

class C1{
	static int mc1(int i, int j) { return i / j; }
	int mc2(int i, int j) {return i % j;}
}


public class FunctionalTest {
    String name = "멤버변수";
	public static void main(String[] args) {
	String name = "메인지역변수";
	C m = (a, b) -> a * b;
	System.out.println(m.calc(10, 2));
	
    //람다식
/*    Math m2 = (first, second) ->first - second;

    System.out.println(m2.calc(10, 2));

    Math m3 = (i, j) -> i + j;
    System.out.println(m.calc(10, 2));

    Math m4 = (i, j) -> i / j;
    System.out.println(m.calc(10, 2));
 */     
    //Math m5 = (i, j) -> C1.mc1(i, j); // 람다식의 매개변수를 외부클래스 메소드에 매개변수 전달하고
     Math m5 = C1::mc1; //위와 같음 , 클래스명::static매소드명
    
    //외부클래스 메소드가 실행한 결과 리턴 
    System.out.println(m5.calc(10, 2));//5
    
   // Math m6 = (i, j) -> new C1().mc2(i, j); 
    Math m6 = new C1()::mc2; // non-static메소드 사용 방법 
    System.out.println(m6.calc(10, 20));
/*    A a1 = () -> 1;
    System.out.println(a1.ma());
    B b1 = (a) -> {
    	String name2 = "람다";
    	System.out.println(name);
    	System.out.println("람다식 실행"); // 람다식을 포함하고 있는 지역변수 사용 가능  
    	// static변수 --> 클래스명.static변수명
    	// non-static변수 --> new 클래스명().non-static변
    	System.out.println(new FunctionalTest().name);
    	return a*a;
    	};
        System.out.println(b1.mb(10));
 */ 
		
	}

}