코틀린

중첩 클래스와 내부 클래스

huzit 2023. 9. 18. 13:23
728x90

중첩 클래스

다른 클래스에 클래스 중첩할 수 있다.

class Outer{
    private val bar = 1
    class Nested{
        fun foo() = 2
    }
}

Outer.Nested.foo()

또한 인터페이스도 중첩할 수 있다. 클래스와 인터페이스로 만들 수 있는 모든 조합이 가능하다. 

interface OuterInterface{
    class InnserClass
    interface InnerInterface
}

class OuterClass{
    class InnerClass
    interface InnerInterface
}

내부 클래스

중첩 클래스와 같지만 외부 클래스 멤버에 접근할 수 있다. 내부 클래스는 외부 클래스 객체에 대한 레퍼런스를 갖는다.

class Outer{
    private val bar = 1
    inner class Inner{
        fun foo() = bar
    }
}

Outer.Inner.foo()

익명 내부 클래스

익명으로 내부 클래스를 생성할 수 있다.

binding.mainButton.setOnClickListener(object : View.OnClickListener{
    override fun onClick(p0: View?) {
        TODO("Not yet implemented")
    }
})

객체가 함수형 자바 인터페이스의 인스턴스라면, 람다 식을 사용해서 생성할 수 있다.

binding.mainButton.setOnClickListener { TODO("Not yet implemented") }
728x90