JAVA

Anonymous class in Java

seoca 2019. 2. 20. 07:27



1. Anonymous class has no name so, It allows a base class to implement without a name.

2. It is often used for overriding the methods of a class or interface. 

3. It can be used only once.



Person p = new Person(); // semi-colon 을 지우고 중괄호를 열어서 코드를 시작해준다.


public void greeting() // greeting method를 overriding해준다.

// overriding은 subclass에서만 사용가능하기에 p가 person class의 자식클래스에서 왔다는 것을 알수있다.

// 이곳에서는 Person의 subclass를 찾아볼수가 없는데 그래서 anonymous class 즉, 익명클래스라고 불린다.

// overriding 이나 interface 처럼 subclass 에서 구현되어져야하는 곳에서 익명클래스는 주로 쓰이게된다.


Example code


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
33
34
35
36
37
38
39
//1. implementing an anonymous class through a base class
class Person {
    public void greeting(){
        System.out.println("Hello");
    }
}
 
//2. implementing an anonymous class through an interface
// The interface is not allowed to implement the actual code inside
interface Utility{
    void showInfo();
}
 
 public class Main{
    public static void main(String[] args){
 
        //p is instantiated from the subclass of Person class
        Person p = new Person(){//because overriding can only be written in subclass
            public void greeting(){
                System.out.println("Hello anonymous class");
            }
        };
 
        p.greeting();
 
        // generally, the interface needs another class to implement.
        // but by using an anonymous class, it can be instantiated.
        Utility util = new Utility() {
            @Override
            public void showInfo() {
                System.out.println("It's implemented by an interface");
            }
        };
 
        util.showInfo();
 
    }
}
 
cs




Result

1
2
3
Hello anonymous class
It's implemented by an interface
cs





Reference 

https://www.youtube.com/watch?v=Yyr451RBB6g