-
[Kotlin] Nested ClassKotlin/Class and objects 2021. 12. 13. 18:12
[Java] 내부 클래스
코틀린 내부 클래스 https://hellose7.tistory.com/119 [kotlin] Nested Class [Java/Nested Class] - [Java] 내부 클래스 [Java] 내부 클래스 non-static 내부 클래스 인스턴스 생성법 반드시 외부 클래스 인스턴..
hellose7.tistory.com
[Java] 익명 클래스
-익명 클래스란 class A 를 상속받아 어떠한 기능을 하는 class B를 만들어야 한다고 가정하자. class B extends A로 클래스 B를 선언한 뒤에 new B를 통해 객체를 생성한다. 만약 프로그램에서 클래스 B는
hellose7.tistory.com
내부 클래스 개념과 문법은 위의 자바 포스팅을 참고
코틀린의 내부 클래스
class Outer { class StaticNested inner class Inner }inner 키워드를 사용하지 않으면 static 내부 클래스(Inner 클래스) 로 되고
inner 키워드를 사용해야 non-static 내부 클래스(Nested 클래스) 가 된다.
코틀린 바이트 코드

인스턴스 생성법
class Outer { inner class Inner class StaticNested } fun main() { val outer = Outer() println(outer) val inner = outer.Inner() println(inner) val nested= Outer.StaticNested() println(nested) }
자바와 동일하게 Inner(non static)클래스의 인스턴스는 외부 클래스의 인스턴스를 통해 Inner 객체를 생성하고
Nested(static)클래스의 인스턴스는 외부 클래스의 인스턴스 필요없이 자체적으로 인스턴스를 생성가능하다.
Inner class에서 사용할 수 있는 외부 클래스 인스턴스 this 키워드
Java : 외부클래스명.this
Kotlin: this@외부클래스명
class Outer { val outerString = "outer 스트링" inner class Inner { val innerString = "inner 스트링" fun printOuterString() { println(this@Outer.outerString) } fun printInnerString() { println(this.innerString) //println(this@Inner.innerString)과 동일 } } } fun main() { val outer: Outer = Outer() val inner: Outer.Inner = outer.Inner() inner.printOuterString() inner.printInnerString() }
자바와 다르게 코틀린에서는 Inner class 내부에 Nested class를 선언하지 못한다
Java

Kotlin

object 선언식도 자바의 Nested (static)클래스로 변경되기 때문에, Inner (non staitc)클래스 내부에 object 선언식을 사용할 수 없다. 자바 문법상의 오류는 없는데 코틀린에서 이를 제한한 의도를 정확히 모르겠다.
Kotlin

익명 클래스
코틀린에서는 object를 이용하여 일회성 객체를 만들 수 있다.
https://hellose7.tistory.com/120
[Kotlin] object
hellose7.tistory.com
코틀린에서는 static 키워드를 지원하지 않는다. Nested 클래스가 static 클래스로 처리되고, object 선언식도 static 클래스로 처리된다. 자바의 내부 클래스를 이해하기 위해서는 코틀린의 Inner, Nested class , object 선언식, companion object의 개념을 모두 이해해야 한다.
[Kotlin/Class and objects] - [Kotlin] object
'Kotlin > Class and objects' 카테고리의 다른 글
[Kotlin] object (0) 2021.12.13 [Kotlin] object, companion object (0) 2021.08.16