ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Kotlin] object, companion object
    Kotlin/Class and objects 2021. 8. 16. 15:44

    1. object
    - object expression
    오브젝트 표현식은 명시적으로 class 선언을 하지 않은 채로 익명 클래스의 오브젝트를 만든다.
    이러한 인스턴스들은 클래스 이름이 아닌, 표현식으로 정의되기 때문에 anonymous object라고 불린다.
    일회성에 적합
    클래스 바디 구조처럼 선언하고 앞에 =으로 표현식으로 정의
    object expressionsAny를 상속받는다.
    !!object에는 생성자가 허용되지 않는다.

    //공부 필요
    Using anonymous objects as return and value types
    https://kotlinlang.org/docs/object-declarations.html#using-anonymous-objects-as-return-and-value-types
    inline 선언

    function에 정의한 varobject내에서 사용할 수 있다.

    - object declaration
    싱글톤 패턴
    객체 접근 시점에 객체가 생성된다.
    object키워드 뒤에 이름이 따른다.
    object 오브젝트이름{ }
    이름으로 호출
    선언 안에 property, function, init{}이 들어갈 수 있다.
    //The initialization of an object declaration is thread-safe and done on first access.

    -object expressions vs declarations

    Object expressions are executed (and initialized) immediately, where they are used.
    Object declarations are initialized lazily, when accessed for the first time.
    A companion object is initialized when the corresponding class is loaded (resolved) that matches the semantics of a Java static initializer.

    - companion object
    ??companion objectstatic이 아니며 사용하는 입장에서 static으로 동작하는 것처럼 보일 뿐임!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    인터페이스 내에도 companion object 선언 가능

    조상, 자손 클래스 companion object 내부의 멤버가 같은 이름이면 조상의 멤버는 가려진다.
    클래스 내부에 정의되는 object의 특수한 형태(하나만 존재가능)

    포함된 companion object가 이름이 없다면 클래스.companion멩버 로 사용가능
    The name of a class used by itself (not as a qualifier to another name) acts as a reference to the companion object of the class (whether named or not)

    /*
    더 공부하기
    Class members는 해당되는 companion objectprivate 멤버에 접근 가능

    Note that even though the members of companion objects look like static members in other languages, at runtime those are still instance members of real objects, and can, for example, implement interfaces:
    However, on the JVM you can have members of companion objects generated as real static methods and fields if you use the @JvmStatic annotation.
    See the Java interoperability section for more detail.

    인스턴스 없이 호출될 수 있는 함수를 사용할 필요가 있으면
    그렇지만 한 클래스의 internal로의 접근이 필요하면(팩토리 메서드와 같은)
    클래스 안의 object declaration으로 멤버로 사용할 수 있다.

    특히, 클래스 안에 companion object를 선언하면, 클래스 이름만으로 그것의 멤버에 접근할 수 있다.
    */

     


    //object expression, object declaration
    //2-1
    interface TestInterface {
    fun method()
    }

    open class TestClass() {
    open fun superMethod() { //open 사용해야 extend가능
    println("superclass's method()")
    }
    }

    //2-2
    open class A(x: Int) {
    public open val y: Int = x
    }

    interface B { /*...*/ }

    //3 다시보기
    class C {
    private fun getObject() = object {
    val x: String = "x"
    }

    fun printX() {
    println(getObject().x)
    }
    }

    fun main() {
    // object practice
    //1. Creating anonymous objects from scratch
    val obj = object {
    val hello = "Hello"
    val world = "World"

    //object expressions extend Any, so `override` is required on `toString()`
    override fun toString() = "$hello $world" //Lambda expression
    }
    //println(obj.toString())

    //2. create an object of an anonymous class that inherits from some type (or types)
    //2-1
    //상속 및 구현
    var obj2 = object : TestInterface {
    override fun method() {
    println("method() 구현완료")
    }
    }
    //obj2.method1()
    //obj2.method2()

    //상속 및 오버라이딩
    var obj3 = object : TestClass() {
    override fun superMethod() {
    println("override superclass's method")
    }

    fun subMethod() {
    println("subclass's method")
    }
    }
    //obj3.superMethod()
    //obj3.subMethod()

    //2-2
    //superclass에 생성자가 있는 경우, 적절한 생성자 파라메터를 전달해야함
    var obj4 = object : A(10), B {
    override val y: Int = 20
    }

    //3. 공부 필요

    //4. 함수의 var을 함수의 scope내에서 사용가능
    /*
    fun countClicks(window: JComponent) {
    var clickCount = 0
    var enterCount = 0

    window.addMouseListener(object : MouseAdapter() {
    override fun mouseClicked(e: MouseEvent) {
    clickCount++
    }

    override fun mouseEntered(e: MouseEvent) {
    enterCount++
    }
    })
    // ...
    }
    */




    }

    'Kotlin > Class and objects' 카테고리의 다른 글

    [Kotlin] object  (0) 2021.12.13
    [Kotlin] Nested Class  (0) 2021.12.13

    댓글

Designed by Tistory.