학습목표 :Anonymous Classes 를 정의할 수 있다.
https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
Anonymous Classes Sample
package team.study._anonymous_classes;
public class HelloWorldAnonymousClasses {
interface HelloWorld {
public void greet();
public void greetSomeone(String someone);
}
public void sayHello() {
/* 전통적인 인터페이스 구현체 */
class EnglishGreeting implements HelloWorld {
String name = "world";
public void greet() {
greetSomeone("world");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Hello " + name);
}
}
HelloWorld englishGreeting = new EnglishGreeting();
/* 익명 클래스 사용 */
HelloWorld frenchGreeting = new 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);
}
};
/* 익명 클래스 사용 */
HelloWorld spanishGreeting = new HelloWorld() {
String name = "mundo";
public void greet() {
greetSomeone("mundo");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Hola, " + name);
}
};
/* 인터페이스 구현체 실행 */
englishGreeting.greet();
/* 익명클래스 실행 */
frenchGreeting.greetSomeone("Fred");
/* 익명클래스 실행 */
spanishGreeting.greet();
}
public static void main(String... args) {
HelloWorldAnonymousClasses myApp =
new HelloWorldAnonymousClasses();
myApp.sayHello();
}
}
'Java > Lambda Expressions' 카테고리의 다른 글
예제로 배워보기 - 람다 & MethodReference(더블콜론) (1) (0) | 2021.07.18 |
---|---|
예제로 배워보기 - 람다(1) (0) | 2021.07.17 |
[표준 API] 함수적 인터페이스 : @FunctionalInterface (0) | 2021.05.23 |
[Lamda Expression] Anonymous Classes -> Lamda Expression (0) | 2021.05.23 |
[Lambda Expressions] 소개 (0) | 2021.05.23 |