Java/Lambda Expressions

[Anonymous Classes] 람다가 있기전 익명클래스가 있었다.

고인돌개발자 2021. 5. 23. 17:30

학습목표 :Anonymous Classes 를 정의할 수 있다.

 


https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

 

Anonymous Classes (The Java™ Tutorials > Learning the Java Language > Classes and Objects)

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated

docs.oracle.com

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();
    }            
}