Kotlin 에서의 Class 사용에 대해서 알아보도록 하겠습니다.

Java 와의 호환성이 Kotlin 의 큰 장점으로 부곽되는 만큼 Java 와 비교하게 되는 부분이 있습니다.

 

Kotlin 에서 Class는 Java와 같이 아래처럼 사용합니다.

class Person{ }

그러나 Java 와 다르게 Body 가 없이 아래와 같이 사용될 수도 있습니다.

class Person

 

Kotlin에서는 primary constructor 과 하나 이상의 secondary constructor 를 가질 수 있습니다.

primary constructor 는 class 선언시 함께 가능합니다.

constructor 키워드는 생략 가능합니다.

annotation 이나 접근자(private, pubilc 등) 와 함께 사용되는 경우 생략할 수 없습니다.

class Person constructor(firstName: String) {

}
class Person(firstName: String) {

}

primary constructor

primary constructor 는 어떤 코드도 포함하지 않으므로 initializer block 을 사용하여 초기화 코드를 구현하면 됩니다.

constructor 가 불리면 객체 생성이 되면서 initializer block 이 불립니다.

primary constructor 의 parameter 는 class 내 어디서든(init 블럭이나 속성값 초기화) 사용 가능합니다.

class Person(name: String) {
    val nameInfo = "Name : $name".also(::println)

    init {
        println("First initializer block that prints ${name}")
    }

    val secondProperty = "Second property: ${name.length}".also(::println)

    init {
        println("Second initializer block that prints ${name.length}")
    }
}

 

secondary constructor

constructor 키워드가 반드시 사용되어야 합니다.

class Person {
    constructor(parent: Person) {
        parent.children.add(this)
    }
}

primary constructor 가 있는 경우 모든 second constructor는 primary constructor 에게 위임해야 합니다. 동일 클래스 내에서 다른 생성자로의 위임은 this 키워드를 사용합니다.

class Person(val name: String) {
    constructor(name: String, parent: Person) : this(name) {
        parent.children.add(this)
    }
}

initializer block의 코드는 primary constructor 의 일부가 된다. primary constructor 로의 위임은 secondary constructor 코드 실행 전에 실행되므로 모든 initializer block 의 코드는 가장 먼저 실행됩니다.

class Constructors {
    init {
        println("Init block")    // 먼저 실행됨
    }

    constructor(i: Int) {
        println("Constructor")   // 나중에 실행됨
    }
}

 

class의 instance 생성하기

class의 instance 를 생성하는데 JAVA에서는 new 키워드를 사용했다면, Kotlin 에서는 constructor 호출만 하면 됩니다.

val invoice = Invoice()

val customer = Customer("Joe Smith")

 

class 상속받기

Kotlin 에서 class 를 상속받기 위해서는 아래와 같이 사용할 수 있습니다.

C++과 같이 : 기호를 사용하는데 super class의 클래스명에 괄호기호가 붙는 점이 다르네요

물론 함수 override 도 아래와 같이 할 수 있습니다.

open annotation은 class로부터의 상속이 가능하다는 의미입니다. Kotlin에서는 모든 class가 default로 final 로 선언됩니다

open annotation을 사용하는 경우에만 상속이 가능합니다.

method 의 경우에도 open annotation이 있는 method 만 override 가능합니다.

open class Base {
    open fun v() {}
    fun nv() {}
}
class Derived() : Base() {
    override fun v() {}
}

변수의 경우 val 변수(Read only) 를 var 변수로 재정의 할 수 있지만, 반대는 안됩니다.

interface Foo {
    val count: Int
}

class Bar1(override val count: Int) : Foo

class Bar2 : Foo {
    override var count: Int = 0
}

 

 

+ Recent posts