728x90

자바에서는 A 클래스 안에 B 클래스를 정의하면 B 클래스는 자동으로 내부 클래스가 되었다.
하지만 코틀린에서는 반대다.
한 클래스안에 다른 클래스를 정의하면 기본적으로는 중첩 클래스가 되고,
내부 클래스로 만들고 싶다면 inner 키워드로 클래스를 선언해야 한다.
내부 클래스는 기본적으로 외부 클래스를 참조하게 되지만 중첩 클래스는 그렇지 않다.


class Outer {
    val a = "Outside Nested class."

    class Nested {
        // Outer Class 변수에 접근할 수 없다.
        val b = "Inside Nested class."
        fun callMe() = "Function call from inside Nested class."
    }
}

fun main(args: Array<String>) {
    // accessing member of Nested class
    println(Outer.Nested().b) // 자바의 static 중첩 클래스와 동일하다.

    // creating object of Nested class
    val nested = Outer.Nested()
    println(nested.callMe())
}
 




'안드로이드 > Kotlin 문법' 카테고리의 다른 글

[코틀린] ArrayList, mutableListOf  (0) 2021.06.14
[코틀린] Inner Class  (0) 2020.08.21
코틀린 클래스  (0) 2020.05.06
코틀린 null 안전과 예외  (0) 2020.05.05
코틀린 object  (0) 2020.01.19
블로그 이미지

Link2Me

,