Post

(Kotlin/Java) Inner Class / Nested Class

Kotlin 중첩 클래스 / 내부 클래스

아무 변경자를 붙이지 않고 클래스의 내부에 다시 정의된 클래스는 자바의 static 중첩 클래스와 동일하다. 내부 클래스로 변경해 바깥쪽 클래스에 대한 참조를 포함하도록 하려면 inner 변경자를 붙여준다. 내부 클래스에서 바깥쪽 클래스의 인스턴스에 접근하기 위해서는 this@를 붙여주어야 한다.

1
2
3
4
5
6
class Outer {
inner class Inner {
fun getOuterReference() : Outer = this@Outer
}
}

Java 중첩 클래스 / 내부 클래스

최상위에 정의하는 class에 static을 붙이면 에러가 발생하는데, 이는 staticclass로 만들 수 없어서가 아니라 이미 java static이기 때문이다.

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
class Nested {
//int resource = 0;    \_Nested에서 사용 불가
static int static\_resource = 1;

  

/\*  static이니까 바깥쪽 클래스라고 해도 static 멤버에만 접근할  있다. \*/
static class \_Nested {
//int \_resource = 2;    Nested에서 접근 불가
static int \_static\_resource = 3;

  

public static void \_use(){
//System.out.println(resource); 접근 불가
System.out.println(static\_resource);
}
}

  

public void use(){
\_Nested.\_use();
// System.out.println(\_resource); 접근 불가
System.out.println(\_Nested.\_static\_resource);
}
}

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
class Inner {
int resource = 0;
static int static\_resource = 1;

  

/\* 내부 클래스는 바깥쪽 클래스에 대한 참조를 묵시적으로 포함한다. \*/
class \_Inner {
int \_resource = 2;
//inner class에서는 static 선언 불가.
//static int \_static\_resource = 3;

  

public void \_use(){
System.out.println(resource);  // 접근 가능
System.out.println(static\_resource);
}
}

  

public void use(){
\_Inner i = new \_Inner();
i.\_use();
System.out.println(i.\_resource);
//System.out.println(\_Inner.\_static\_resource);
}
}

1
2
3
4
5
6
7
8
9
10
public class ch4 {
@Override
public static void main(String[] args) {
Nested n = new Nested();
n.use();
Inner i = new Inner();
i.use();
}
}

This post is licensed under CC BY 4.0 by the author.