본문 바로가기
개발/자바

Java ) 인터페이스를 객체로 만들기

by kakk789 2022. 8. 4.

인터페이스를 객체로 만들기

1. Return Type이 void 일 경우

인터페이스 선언

  • 예시는 추상 메소드가 하나 존재하는 클래스 (함수형 인터페이스, @FunctionalInterface)
@FunctionalInterface
public interface AnimalSound {
	public void sound();
}

 

예시 a) 선언과 동시에 구현 필요

	AnimalSound as = new AnimalSound() {
		@Override
		public void sound() {
			System.out.println("추상메소드 바로 구현");
		}
	};
	as.sound();

 

예시 b) 람다식으로 표현

= new 객체 생성 부분을 () -> { }  과 같이 람다식으로 표현
	AnimalSound as1 = () -> {
		System.out.println("람다식");
	};
	as1.sound();

 

2. Return Type이 존재 할 경우(return type int)

  • 함수 리턴 하듯이 return 문을 써주면 가능
@FunctionalInterface
public interface Math {
	public int calc(int a, int b);
}
Math sub = (a,b)->{ 
    int r;
    r=a-b;
    return r;
};

Math multi = (a,b)->{
    return a*b;
};

 

반응형

댓글