추상 메소드가 하나인 인터페이스의 익명 클래스 객체를 만들 때 사용가능
public class C01lambda {
public static void main(String[] args) {
//람다식
MyInterface01 o1 = (x, y) -> {
System.out.println(x + y + "람다");
};
//익명 클래스
MyInterface01 o2 = new MyInterface01() {
@Override
public void method1(int x, int y) {
System.out.println(x + y);
}
};
}
}
//lambda expression(람다식)
//추상 메소드가 하나인 인터페이스의 익명 클래스 객체를 만들 때 사용가능
//추상 메소드가 하나인 인터페이스를 Functional Interface 라고함
@FunctionalInterface //해당 인터페이스가 추상메소드가 하나인지 컴파일러를 통해 검증하도록 하는 어노테이션 / 생략 가능
interface MyInterface01{
void method1(int x, int y);
}
매개변수 없는 람다식
public class C02lambda {
public static void main(String[] args) {
//lambda 형식
//(파라미터) -> { 메소드 몸통 }
MyInterface02 o1 = () -> {
System.out.println("람다 완성");
};
o1.method();
//메소드내 코드가 한줄이면 {} 중괄호 생략 가능
MyInterface02 o2 = ()-> System.out.println("메소드내 코드가 한줄이면 {} 중괄호 생략 가능");
o2.method();
}
}
@FunctionalInterface
interface MyInterface02 {
//파라미터 없는 추상 메소드
//리턴도 없음
void method();
}
매개변수가 하나 또는 여러개 있는 람다식
public class C03parameter {
public static void main(String[] args) {
//매개변수가 여러개 있는 경우
//(매개변수) -> { 메소드 몸통 작성 }
MyInterface03 o1 = (x, y) -> {
System.out.println(x+y);
};
//매개변수가 하나인 경우
//()생략 가능
MyInterface031 o2 = x -> {
System.out.println(x);
};
}
}
@FunctionalInterface
interface MyInterface03 {
void method(int x, int y);
}
@FunctionalInterface
interface MyInterface031 {
void method(int x);
}
리턴 타입이 있는 람다식
public class C05return {
public static void main(String[] args) {
//return 있는 람다식
MyInterface05 o1 = () -> {
System.out.println("여러 명령문들");
return 1;
};
//명령문이 한줄이면 이런식으로 return 값 생략해서 가능
MyInterface05 o2 = () -> 1;
}
}
@FunctionalInterface
interface MyInterface05 {
//리턴 타입이 있는 추상 메소드
int method();
}
메소드 참조 형식의 람다식 (methode reference)
public class C06methodReference {
public static void method06(int x){
}
public static void method061(int x, int y){
}
public static void main(String[] args) {
MyInterface06 o1 = a -> C06methodReference.method06(a);
//메소드 참조(methode reference)
MyInterface06 o2 = C06methodReference::method06;
}
}
//매개변수 1개
interface MyInterface06 {
void method(int a);
}
//매개변수 여러개
interface MyInterface061 {
void method(int x, int y);
}
반응형
'JAVA > 기본' 카테고리의 다른 글
Stack 스택(LIFO) / Queue 큐(FIFO) (0) | 2023.09.12 |
---|---|
제네릭스 <> (Generic) (0) | 2023.09.07 |
인터페이스(interface) implements (0) | 2023.09.01 |
추상 클래스 (abstract class) / 추상 메소드 (abstract method) (0) | 2023.08.30 |
상속 Extends / 오버라이딩(overriding) / 오버로딩(Overloading) (0) | 2023.08.23 |