익명중첩클래스:

클래스나 인터페이스에 정의된 메서드를 Overriding하여 사용하고자 할 때 상속을 받은 클래스를 만들지 않고자 할 때 사용한다. 주로 메서드의 매개변수로 객체를 넘길 때 사용한다.

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
40
41
42
43
44
45
fun main(args : Array<String>){
    var t1 = TestClass2()
    method100(t1)
 
    var t2 = TestInter2()
    method200(t2)
    
}
 
// 추상클래스 정의
abstract class TestClass1{
 
    abstract fun test_method1()
 
}
 
// 인터페이스 정의
interface TestInter1{
    fun inter_method1()
}
 
// TestClass1의 test_method1메서드를 오버라이드한다.
class TestClass2 : TestClass1(){
    override fun test_method1() {
        println("TestClass2의 test_method1")
    }
}
 
// TestInter1의 inter_method1메서드를 오버라이드한다.
class TestInter2 : TestInter1{
    override fun inter_method1() {
        println("TestInter1의 inter_method1")
    }
 
}
 
// 추상클래스를 상속받은 메서드
fun method100(a1 : TestClass1){
    a1.test_method1()
}
 
// 인터페이스를 상속받은 메서
fun method200(a1 : TestInter1){
    a1.inter_method1()
}
cs



추상클래스나 인터페이스를 상속받은 메서드를 사용하려면 22~35번의 class를 만들어 줘야한다. 왜냐하면 추상클래스나 인터페이스는 객체를 생성할 수 없기 때문이다.

위처럼 class(22~35번줄) 작성하면 코드양도 많아지고 어렵다.

class를 사용하지 않을려면 아래처럼 작성하면 된다.


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
40
41
fun main(args : Array<String>){
 
    // 익명 중첩 클래스 사용
    method100(object : TestClass1(){
        override fun test_method1() {
            println("익명 중첩 클래스의 test_method1")
        }
    })
 
    // 익명 중첩 클래스 사용
    method200(object : TestInter1{
        override fun inter_method1() {
            println("익명 중첩 클래스의 test_inter1")
        }
 
    })
}
 
// 추상클래스 정의
abstract class TestClass1{
 
    abstract fun test_method1()
 
}
 
// 인터페이스 정의
interface TestInter1{
    fun inter_method1()
}
 
 
// 추상클래스를 상속받은 메서드
fun method100(a1 : TestClass1){
    a1.test_method1()
}
 
// 인터페이스를 상속받은 메서드
fun method200(a1 : TestInter1){
    a1.inter_method1()
}
 
cs


'코틀린' 카테고리의 다른 글

중첩클래스(내부클래스)  (0) 2018.11.26

+ Recent posts