우리는 JdbcTemplate을 사용하는 과정에서 익명 클래스와 람다식이라는 자바 문법을 사용했습니다. 익명 클래스는 자바의 초창기부터 있던 기능이고, 람다식은 자바 8에서 등장한 기능입니다. 다음 키워드를 사용해 몇 가지 블로그 글을 찾아보세요! 아래 질문을 생각하며 공부해보면 좋습니다! 😊
[키워드]
익명 클래스 / 람다 / 함수형 프로그래밍 / @FunctionalInterface / 스트림 API / 메소드 레퍼런스
[질문]
// 부모 클래스
class Animal {
public String bark() {
return "동물이 웁니다";
}
}
public class Main {
public static void main(String[] args) {
// 익명 클래스 : 클래스 정의와 객체화를 동시에. 일회성으로 사용
Animal dog = new Animal() {
@Override
public String bark() {
return "개가 짖습니다";
}
}; // 단 익명 클래스는 끝에 세미콜론을 반드시 붙여 주어야 한다.
// 익명 클래스 객체 사용
dog.bark();
}
}
int[] arr = new int[5]
Arrays.setAll(arr, (i) -> (int) (Math.random() * 5) + 1);
// (i) - (int) (Math.random() * 5) + 1 람다식을 메서드로 표현
int method() {
return (int) (Math.random() * 5) + 1;
}
자바의 람다식은 왜 등장했을까?
불필요한 코드를 줄이고, 가독성을 높이기 위함
함수형 인터페이스의 인스턴스를 생성하여 함수를 변수처럼 선언하는 람다식에서는 메서드의 이름이 불필요하다고 여겨져서 이를 사용하지 않고, 대신 컴파일러가 문맥을 살펴 타입을 추론
또한 람다식으로 선언된 함수는 1급 객체이기 때문에 Stream API의 매개변수로 전달이 가능해짐
람다식과 익명 클래스는 어떤 관계가 있을까?
람다식의 문법은 어떻게 될까?
익명 함수를 이용한 구현
public class Example {
interface Math {
int sum(int n1, int n2);
}
static class MyMath implements Math {
public int sum(int n1, int n2) {
reutrn n1 + n2;
}
}
static int doSomething(Math math) {
return math.sum(10, 20);
}
pulbic static void main(String[] args) {
Math math = new MyMath();
int result = doSomething(math);
System.out.println(result); // 30
}
}
람다식을 이용한 구현
public class Example2 {
interface Math {
int sum(int n1, int n2);
}
static int doSomething(Math math) {
return math.sum(10, 20);
}
public static void main(Stirng[] args) {
int result = doSomething((n1, n2) -> n1 + n2); // Lambda
System.out.println(result); // 30
}
}
→ 불필요한 선언부들이 모두 생략되어 있고, 인터페이스 함수의 구현부만 정의하고 있어 코드가 간결!
(parameter) -> expression