티스토리 뷰

Programming/Kotlin

Kotlin Class

Albothyl 2022. 4. 16. 11:18
  1. Constructor

    1. class Person constructor(firstName: String) { /*...*/ }
      
      // 생성자에 별도의 annotation이나 접근 제한자가 없으면 생성자를 생략 가능.
      class Person(firstName: String) { /_..._/ } 
      
      // 별도의 annotation이나 접근 제한자가 있는 생성자
      class Customer public @Inject constructor(name: String) { /*...*/ }
      
      // 기본 생성자에서 속성을 선언할 수 있다.
      class Person(val firstName: String, val lastName: String, var age: Int)
      class Person(val firstName: String, val lastName: String, var age: Int,) // 마지막에 ","를 추가할 수 있다.
      
      // 기본 생성자에서 기본값을 설정할 수 있다.
      class Person(val firstName: String, val lastName: String, var isEmployed: Boolean = true)
      
      // 생성자를 private로 설정하여 공개를 제한할 수 있다.
      class DontCreateMe private constructor () { /*...*/ }
  2. Secondary constructors

    // 기본 생성자가 있는 경우 각 보조 생성자는 다른 보조 생성자를 통해 직접 또는 간접적으로 기본 생성자에 위임해야 한다. 
    // 동일한 클래스의 다른 생성자에 대한 위임은 다음 this키워드를 사용하여 수행된다.
    class Person(val name: String) {
        val children: MutableList<Person> = mutableListOf()
        constructor(name: String, parent: Person) : this(name) {
            parent.children.add(this)
        }
    }
  3. Initialization

    1. 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}")
           }
      }
  4. Instance

    val invoice = Invoice()
    val customer = Customer("Joe Smith") // 인스턴스를 생성할때 new 키워드가 없다.
  5. Abstract Class

    abstract class Polygon {
        abstract fun draw() // body를 구현하지 않고 선언만 한다.
    }
    
    class Rectangle : Polygon() { // 상속받은 class에서 abstract method의 body를 구현한다.
        override fun draw() {
            // draw the rectangle
        }
    }
  6. Open Class

    // kotlin의 class는 기본적으로 상속이 막혀있다. 상속을 가능하게 하려면 open 키워드를 사용해야 한다.
    open class Polygon {
        open fun draw() {
            // some default polygon drawing method
        }
    }
    
    open class SonOfPolygon {
        override open fun draw() {
            // some default polygon drawing method
        }
    }
    
    abstract class WildShape : Polygon() {
        // abstract class에서는 non-abstract를 abstract로 재정의 할 수 있다.
        // 자식 class에서 override를 강제해야 할 경우에 이렇게 사용하는것 같다.
        abstract override fun draw()
    }

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

Kotlin Conditions  (0) 2022.04.23
Kotlin Operator  (0) 2022.04.23
Kotlin Visibility Modifiers  (0) 2022.04.16
Kotlin Variable  (0) 2022.04.16
Kotlin DataType  (0) 2022.04.15
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함