티스토리 뷰

익명 클래스

일회성으로 1개의 객체를 생성하기 위한 클래스

- 클래스 정의와 동시에 객체를 생성할 수 있음


슈퍼 클래스를 상속받거나 인터페이스를 구현하도록 익명 클래스를 정의

- new 클래스/인터페이스 ( ) { … }

- 중괄호는 익명 클래스의 몸체



클래스를 상속받는 익명 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class AnonymousTest {
    public static void main(String args[]) {
        CSuper sub = new CSuper() {
            public int b = 20;
 
            public void method1() {
                System.out.println("sub1");
            }
 
            public void method3() {
                System.out.println("sub3");
            }
        }
 
        sub.method1();
        sub.method2();
        System.out.println(sub.a);
        ... ...
    }
}
 
class CSuper {
    public int a = 10;
 
    public void method1() {
        System.out.println("super1");
    }
 
    public void method2() {
        System.out.println("super2");
    }
}
cs



sub1

super2

10



인터페이스를 구현한 익명 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class AnonymousTest {
    public static void main(String args[]) {
        MyInterface sub = new MyInterface() {
            public void method() {
                System.out.println("sub1");
            }
        }
 
        sub.method();
    }
}
 
interface MyInterface {
    public void method();
}
cs


공지사항
최근에 올라온 글
Total
Today
Yesterday