Local classes except that they do not have a name.
이름을 가지고 있지 않는 local class 이다.
Anonymous class는 코드를 간결하게 하고, class 선언과 instantiate를 동시에 할 수 있다는 장점이 있다.
아래와 같은 interface가 있을 때
interface HelloWorld
{
public void greet();
public void greetSomeone(String someone);
}
다음과 같은 HelloWorld Anonymous class를 만들 수 있다.
HelloWorld frenchGreeting = new HelloWorld()
{ // (1) 'new' operator (2) interface name: HelloWorld
String name = "tout le monde";
public void greet()
{
greetSomeone("tout le monde");
}
public void greetSomeone(String someone)
{
name = someone;
System.out.println("Salut " + name);
}
};
Lambda expression은 method가 1개인 interface를 구현할 때 유용하다.
Lambda expression은 다음과 같다.
(매개변수, ...) -> { 실행문 }
다음은 Lambda expression으로 더하기 빼기를 구현한 예시이다.
public class Calculator
{
// one method interface 생성
interface IntegerMath
{
int operation(int a, int b);
}
// reference type interface를 parameter로 설정
public int operateBinary(int a, int b, IntegerMath op)
{
return op.operation(a, b);
}
public static void main(String... args)
{
Calculator myApp = new Calculator();
IntegerMath addition = (a, b) -> a + b;
IntegerMath subtraction = (a, b) -> a - b;
// lambda expression로 interface 구현
System.out.println("40 + 2 = " + myApp.operateBinary(40, 2, addition));
System.out.println("20 - 10 = " + myApp.operateBinary(20, 10, subtraction));
}
}