익명 내부 클래스 란?
이름을 가지지 않는 클래스
익명 내부 클래스 구현 위치
- 메서드 내부에 구현
- 변수에 대입하여 직접 구현
익명 내부 클래스의 생성 방법
메서드를 호출할 때 생성되거나, 인터페이스 타입 변수에 대입할 때, new 키워드를 사용하여 생성
#1
class Outer{
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("runnable");
}
};
}
public class anonymousInnerClass {
public static void main(String[] args) {
Outer outer = new Outer();
outer.runnable.run();
}
}
#2
class Outer{
public Runnable getRunnable(){
return new Runnable() {
@Override
public void run() {
System.out.println("runnable");
}
};
}
}
public class anonymousInnerClass {
public static void main(String[] args) {
Outer outer = new Outer();
Runnable runnable = outer.getRunnable();
runnable.run();
}
}
출력 결과 => 동일하게
runnable
람다식이란?
함수형 프로그래밍 으로써
순수 함수를 구현하고 호출함으로써 외부(side effect)에 영향을 주지 않고 매개변수만을 사용하도록 만든 함수
함수형 프로그래밍(Functional Programming)?
자료 처리를 수학적 함수의 계산으로 취급하고, 상태와 가변 데이터를 멀리하는 프로그래밍 패러다임
ex) Javascript
예시는 다음과 같다
📃 인터페이스 생성 후 메서드 한개 정의
@FunctionalInterface
public interface MyNumber {
int getMaxNumber(int num1, int num2);
}
public class MyNumberTest {
public static void main(String[] args) {
MyNumber maxNum = (x, y) -> (x >= y) ? x : y;
int max = maxNum.getMaxNumber(10,20);
System.out.println(max);
}
}
출력 결과 =>
20
- 사용하기 간단하다
- 안정적이고 확장성이 뛰어나다
- 병렬처리
📃 StringConcat이라는 인터페이스 생성
@FunctionalInterface
public interface StringConcat {
public void makeString(String s1, String s2);
}
<public class StringConcatImpl implements StringConcat{
@Override
public void makeString(String s1, String s2) {
System.out.println(s1 + " " + s2);
}
}
public class StringConcatTest {
public static void main(String[] args) {
// 람다식(함수형 프로그래밍 방식) 이용
StringConcat concat = (s1, s2) -> System.out.println(s1 + " " + s2);
concat.makeString("hello", "java");
// 익명 내부 클래스 이용
StringConcat concat2 = new StringConcat() {
@Override
public void makeString(String s1, String s2) {
System.out.println(s1 + " " + s2);
}
};
concat2.makeString("hello", "java");
// 아래는 ++
// 객체지향 프로그래밍 방식
StringConcatImpl slImpl = new StringConcatImpl();
slImpl.makeString("hello", "java");
}
}
출력 결과 => 동일하게
hello java
!! 사실 람다식으로 메서드를 구현하고 호출하면 내부적으로 익명 클래스가 생성된다
그렇다면 무슨 차이일까?
📌람다식은 하나의 메서드로 생성해 포함하는 반면에
익명 내부 클래스는 새로운 클래스로 생성된다.