Companion Object 란?
객체를 생성하지 않고도 클래스 내부에 접근할 수 있는 객체,
클래스 내부에 선언하면 클래스 이름만으로 companion object 내부에 선언된 맴버에 접근할 수 있다.
class MyClass {
companion object Factory {
fun create(): MyClass = MyClass()
}
}
companion 키워드로 클래스 내부에 선언할 수 있다. companion객체의 이름은 명시해도 되고 명시하지 않아도 된다.
val instance = MyClass.create()
클래스이름으로만 companion 내부에 선언된 맴버에 참조할 수 있다.
JAVA static 맴버와의 차이
자바의 static은 클래스의 맴버로서 선언되어 독립적인 객체로 사용될 수 없지만
코틀린의 companion object 는 엄연한 객체로서 객체를 생성할 수 있고 독립적으로 활용될 수 있다.
class UkHa {
companion object {
val prop = "컴페니언 = 동반자"
}
}
fun main(){
println(UkHa.prop)
println(UkHa.companion.prop)
val object = UkHa.companion // companion object를 객체로 생성
println(object.prop) // 컴페니언 = 동반자
}
그러면서도 클래스이름만으로 참조할 수 있게 한게 참 편리하고 좋다.
클래스내에 companion object는 하나만 쓰일 수 있다.
두개 이상 만들면
Only one companion object is allowed per class 에러가 난다.
class UkhaClass{
companion object{
val prop1 = "개굴개굴"
fun method1() = "훓뚫훓뚫"
}
companion object{ // -- 에러발생!! Only one companion object is allowed per class
val prop2 = "골골골골"
fun method2() = "갈갈갈갈"
}
}
인터페이스 내에서도 companion object를 정의할 수 있다.
이를 통해서 인터페이스 수준에서 상수항을 정의할 수 있다.
관련된 중요 로직을 컴페니언 객체 내에 기술해서 인터페이스 구현시 이점을 줄 수 있다.
interface UkInterface{
companion object {
val prop = "I'm interface of companion object"
}
}
fun main(){
println(UkInterface.prop)
val obj = UkInterface.Companion
println(obj.prop)
val obj2 = UkInterface
println(obj2.prop)
}
상속시 오버라이드 되는 companion object
부모클래스로 부터 상속을 받은 자식클래스는 부모클래스 내에 companion object 또한 상속 받는다.
이때 자식클래스 내에 정의한 comapnion object가 부모클래스의 companion object와 이름이 같을 경우
호출 했을 때 자식클래스 내에 있는 companion object 의 맴버가 호출된다.
이름이 다르다면 별개로 호출할 수 있다.
open class Parent{
companion object{
val parentProp = "어미"
}
fun method0() = parentProp
}
class Child:Parent(){
companion object{
val childProp = "자식"
}
fun method1() = childProp
fun method2() = parentProp
}
fun main() {
val child = Child()
println(child.method0()) //어미
println(child.method1()) //자식
println(child.method2()) //어미
}
참고
https://www.bsidesoft.com/8187
'Kotlin' 카테고리의 다른 글
Kotlin vs Java (0) | 2021.08.21 |
---|---|
데이터 타입 (0) | 2021.08.19 |
클래스 계층 구조란 무엇인가 (0) | 2021.08.15 |
IntRange 타입과 난수 발생시키기 (0) | 2021.07.28 |
7) 클래스 (0) | 2021.07.20 |