9. Nested & Inner Classes

중첩 클래스

치트시트

  • class Nested: 기본 static nested class (바깥 참조 없음)

  • inner class: 바깥 클래스 참조 필요 시 명시적으로 사용

  • 바깥 클래스 참조: this@Outer

  • 기본 설계: Nested class → 안전 (권장)

  • inner는 꼭 필요할 때만


1) 자바와의 차이

  • Java

    • static class → 바깥 클래스 참조 없음 (권장)

    • non-static inner class → 바깥 클래스 참조 있음 (메모리 누수 우려)

  • Kotlin

    • 기본은 Nested class (static nested와 동일)

    • 바깥 클래스 참조 필요 → inner 키워드 사용


2) 문법 비교


3) 바깥 클래스 참조하기

  • inner 클래스에서 바깥 클래스 멤버 접근 가능

  • this@Outer 문법 사용


4) 권장 가이드

  • Effective Java 가이드에 따라, 가능하면 static nested class 사용

  • 코틀린은 이 원칙을 언어 차원에서 강제 (기본은 static nested)

  • 메모리 누수와 직렬화 문제를 줄일 수 있음


5) 실무 활용 예시

A. Helper 클래스

→ 바깥 클래스 상태에 의존하지 않으므로 Nested class로 선언.

Last updated