본문 바로가기
Kotlin

[코틀린] 클래스 생성자의 이해

by 붕어사랑 티스토리 2021. 7. 20.
반응형

https://kotlinlang.org/docs/classes.html

 

Classes | Kotlin

 

kotlinlang.org

상기 주소 내용을 기반으로 작성합니다.

 

 

 

1. 클래스의 구성

코틀린의 클래스는 크게 3가지 항목으로 구분되어있다.

 

  • 클래스 네임 : 클래스의 이름 정의
  • 클래스 헤더 : 변수의 형태 정의, 주생성자 및 다른 것 포함
  • 클래스 바디 : 중괄호{} 안에 있는 작업들

헤더와 바디는 optional이다. 바디가 없으면 {} 중괄호 생략이 가능하다.

 

 

 

2. 생성자

 

코틀린은 하나의 주 생성자와 하나 이상의 부 생성자를 가질 수 있다.

 

 

주 생성자

주 생성자는 클래스 네임 바로 뒤에 오며 optional type parameter를 가집니다.

 

class Person constructor(firstName: String) { /*...*/ }

만약 주 생성자가 annotation 이나 visibility modifier(public, private 같은 접근지시자)를 가지지 않는다면 constructor를 생략 할 수 있습니다.

class Person(firstName: String) { /*...*/ }

 

 

주 생성자는 안에 코드를 포함 할 수 없습니다. 초기화 코드는 init 키워드로 시작하는 initializer 블록에서만 작성 가능합니다.

init 블록은 아래 코드처럼 코드에서 나타는 순서대로 실행됩니다.

class InitOrderDemo(name: String) {
    val firstProperty = "First property: $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}")
    }
}

 

 

주 생성자의 파라미터는 init 블록에서도 쓰일수 있고, 아래와 같이 클래스 바디 안에 프로퍼티 초기화에도 사용 될 수 있습니다.

class Customer(name: String) {
    val customerKey = name.uppercase()
}

 

 

코틀린은 아래와같이 변수선언과 초기화를 동시에 해줄 수 있습니다.

class Person(val firstName: String, val lastName: String, var age: Int)

이러한 방법은 아래처럼 초기값도 넣어줄 수 있습니다.

class Person(val firstName: String, val lastName: String, var isEmployed: Boolean = true)

 

만약 주 생성자가 아래와 같이 annotation이나 visibility modifier(접근지시자)를 가지고 있으면 아래와같이 명시적으로 constructor를 정의 해 주어야 합니다.

class Customer public @Inject constructor(name: String) { /*...*/ }

 

 

부 생성자

 

코틀린은 부생성자를 가질수 있으며 constructor 키워드를 사용합니다.

 

class Person(val pets: MutableList<Pet> = mutableListOf())

class Pet {
    constructor(owner: Person) {
        owner.pets.add(this) // adds this pet to the list of its owner's pets
    }
}

 

 

부 생성자는 직간접적으로 주 생성자를 호출할 수 있습니다. 이때 this 키워드를 사용합니다.

 

class Person(val name: String) {
    var children: MutableList<Person> = mutableListOf()
    constructor(name: String, parent: Person) : this(name) {
        parent.children.add(this)
    }
}

 

 

부 생성자와 init 블록 순서

 

init블록은 주 생성자의 일부이므로 부 생성자보다 먼저 호출됩니다.

 

 

 

3. 객체 생성

 

코틀린은 new 키워드를 제공하지 않습니다. 아래와 같이 함수 선언하듯이 객체 생성하면 됩니다.

val invoice = Invoice()

val customer = Customer("Joe Smith")

 

 

4. 추상클래스

 

코틀린에서는 자바와 같이 아래처럼 추상클래스를 선언할 수 있습니다.

오버라이딩을 해 줄 경우 override 키워드를 사용합니다.

 

abstract class Polygon {
    abstract fun draw()
}

class Rectangle : Polygon() {
    override fun draw() {
        // draw the rectangle
    }
}

 

만약 추상클래스가 아닌 클래스를 상속받고 싶다면 open 키워드를 이용합니다.

open 키워드를 붙이지 않을 경우 코틀린 클래스는 기본적으로 final class가 되어 상속할 수 없습니다.

 

open class Polygon {
    open fun draw() {
        // some default polygon drawing method
    }
}

abstract class WildShape : Polygon() {
    // Classes that inherit WildShape need to provide their own
    // draw method instead of using the default on Polygon
    abstract override fun draw()
}
반응형

댓글