본문 바로가기
Backend/Java

Anonymous Class (익명 클래스)란? (+ GUI에서의 활용)

by 마진 2021. 5. 22.

 

상속 개념을 통해 자식 클래스는 인터페이스나 부모 클래스를 구현(or 상속)합니다.

 

그렇다면 자식클래스는 항상 별도의 클래스로 만들어줘야 할까요?

 

익명 클래스(Anonymous class)는 이런 궁금증에 대한 답변이 됩니다.

 

 


 

 

 Anonymous class는 말그대로 이름 없이 정의된 클래스를 의미하며 선언을 위한 요소선언 방법은 다음과 같습니다.

 

  • The new operator
  • The name of an interface to implement or a class to extend. 
  • Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression.      Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses.
  • A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.

 

  •  - new 연산자
  •  - 구현할 인터페이스나 상속할 클래스의 이름
  •  - 괄호 : 인터페이스를 구현할 경우, 생성자가 없기 때문에 빈괄호를 사용하면 됩니다.
  •  - 블록 : 클래스 선언부이기 때문에 메소드 선언은 가능하나 수행문 코드 (명령) 작성은 불가능합니다.

                   

   [example]

 

    e.g.)  new InterfaceName() {

                public void exampleMethod(){

                     System.out.println("선언요소 구성예시");

                }

           };

 

 


< 선언 사용 예시 >

 

// Anonymous Class 선언하기

public class ExampleForAnonymous {
	
    interface Animal {
    	void eat(); 			//public abstract  생략
    }
    
    public static void main(String[] args) {
        
        Animal test1 = new Animal(){
            @Override
            public eat(){		//오버라이드시 생략되었던 접근제어자(public) 다시 생성
                System.out.println("밥을 먹습니다.");
            }
        };
        
        Animal test2 = new Animal(){
            @Override
            public eat(){
                System.out.println("풀을 먹습니다.");
            }
        };

        test1.eat();
        test2.eat();
    }
}

 

 

위에서 만든 ExapleForAnonymous 프로그램을 실행하면 콘솔창에 아래와 같이 두 문장이 출력됩니다.

 

 

  밥을 먹습니다.

  풀을 먹습니다.

 

 

Animal 자료형의 참조변수 test1과 test2는 각각 Animal 인터페이스가 다르게 구현된 익명 클래스들의 인스턴스를 저장합니다.

 

 

- 선언되는 익명클래스는 수행문(명령: statements)의 일부이므로 세미콜론으로 종료됩니다.

 

 

 


< Application to GUI program >

 

import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class AnonymousClassApplication extends Frame {
    private static final long serialVersionUID = 1L;
	
    public AnonymousClassApplication(String title) {
        super(title);
        setBounds(700, 200, 200, 100);
        setLayout(new FlowLayout());           //버튼을 좀더 잘보이게 하기 위해 Layout 변경
		
        Button button = new Button("exit this program");
        add(button);
		
        button.addActionListener(new ActionListener() {    //Anonymous class 사용

            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
		
        setVisible(true);
    }
	
	
    public static void main(String[] args) {
        new AnonymousClassApplication("example");
		
    }
}

 

익명 클래스의 활용을 위해 간단한 GUI 프로그램을 작성하였습니다.

 

위처럼 단일 혹은 소수 컴퍼넌트의 명령을 구현할 경우 Anonymous class 를 활용하여 

컴퍼넌트의 이벤트에 대한 event listener 인스턴스를 메소드 매개변수에 직접 선언할 수 있습니다.

 

 

수정이 필요하다면 댓글 부탁드립니다.

 

감사합니다.

 

 

 

<참고>

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