phantasmicmeans 기술 블로그

5. Kotlin - Class 본문

Programming/Kotlin

5. Kotlin - Class

phantasmicmeans 2021. 1. 22. 12:52

Kotlin Classe

기본 생성자

  • 클래스 헤더의 일부이자 클래스별로 최대 1개만 가질 수 있다.
class Person constructor(firstName: String) {
}
  • 어노테이션이나 접근지정자가 없을 때는, 기본생성자의 constructor 키워드를 생략가능하다.
class Person(firstName: String) {
}

Primary Constructor

  • 기본생성자는 코드를 가질 수 없으며, 초기화는 초기봐 블록(init) 안에서 작성해야 한다.
  • 기본생성자의 파라미터는 init 블록 안에서 사용 가능
class Customer(name: String) {
    init {
        logger.info("customer intialized with value ${name}")
    } 
}

Secondary Constructor

  • 클래스 별로 1개 이상의 secondary constructor 를 가질 수 있으며, constructor 키워드로 선언된다.
/**
 * declare secondary constructors, which are prefixed with constructor
 */
class PersonT {
    var children: MutableList<PersonT> = mutableListOf()
    constructor(parent: PersonT) {
        parent.children.add(this)
    }
}
  • 클래스가 primary constructor를 가지고 있다면, 각각의 secondary constructor는 기본 생성자에 직접 or 간접적으로 delegate 해야함
    • this를 이용해서 직접 primary constructor에 delegate 하거나
    • this를 이용해서 다른 secondary constructor를 통해 delegate

예시 1

class PersonA(val name: String) {
    var children: MutableList<PersonA> = mutableListOf()
    /**
    * primary constructor 사용 
    */
    constructor(name: String, parent: PersonA) : this(name) {
        parent.children.add(this)
    }
}

예시 2

fun main() {
    var sangmin = Person("sangmin")
    var sangmin2 = Person("sangmin", sangmin)
}

class Person(val name: String) {
    /**
     * primary constructor 사용
     */
    constructor(name: String, parent: Person) : this(name) {

    }

    /**
     *  첫번째 secondary constructor를 간접적으로 이용하여 primary constructor 호출 
     */
    constructor(): this("sangmin", Person()) {} 
}

Generated Constructor

  • Non-abstract class 가 어떠한 constructor(primary, secondary)도 포함하고 있지 않다면, no-argument인 generated primary constructor를 가지게 된다.
  • 해당 constructor는 default public visibility를 가지고, 마찬가지고 visibility를 변경하려면 constructor 를 선언해주어야함
class DoncreateMe private constructor() { }

'Programming > Kotlin' 카테고리의 다른 글

7. Kotlin - Properties  (0) 2021.01.22
6. Kotlin - Class Inheritance  (0) 2021.01.22
4. Kotlin - Return and Jumps  (0) 2021.01.22
3. Kotlin - Control-Flow  (0) 2021.01.22
2. Kotlin - Null Safety  (0) 2021.01.22
Comments