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
'코틀린' 카테고리의 다른 글
Enum(열거형) 클래스 (0) | 2023.09.18 |
---|---|
제네릭 ( in & out) (0) | 2023.09.14 |
봉인된 클래스 및 인터페이스(Seald Class & Interface) (0) | 2023.04.10 |
데이터 클래스(Data Class) (0) | 2023.03.20 |
확장(Extensions) (0) | 2023.03.07 |