본문 바로가기

Kotlin

Kotlin 도큐먼트: 클래스 선언하고 객체 생성하기

이 문서의 내용

    더보기

    Kotlin에서 클래스는 class 키워드로 선언합니다.

    class Person { }

    클래스 선언 구문은 클래스 이름 클래스 헤더 클래스 본문으로 구성됩니다.

    헤더에는 매개 변수 유형, 생성자 등이 포함되며 본문은 블록({})으로 구성합니다.

    헤더와 본문 정의는 모두 선택 사항이며 본문의 경우 블록({})을 생략 가능합니다.

    class Person

    클래스 생성자, 주 생성자(Primary constuctor)

    Kotlin의 클래스는 주 생성자(Primary constructor)와 하나 이상의 보조 생성자(Secondary constructors)가 있습니다.

    주 생성자는 클래스 헤더클래스 이름 그리고 선택적으로 매개 변수 유형이 따릅니다.

    class Person constructor(firstName: String) { }

    constructor 키워드는 생략하여 다음과 같이 작성 할 수 있습니다.

    class Person(firstName: String) { }

    주 생성자는 클래스 헤더를 사용해 객체와 객체의 프로퍼티를 초기화합니다.

    헤더에서는 객체를 초기화 하기 위한 실행 가능 코드가 입력 될 수 없으며, 필요한 경우 본문에서 입력합니다.

    초기화 블록은 본문에서 init 키워드와 함께 사용됩니다.

    class Person(firstName: String) {
        init {
            println("This first name is $firstName")
        }
    }
    코드 비고
    Line 2 init { } 본문에서 초기화 블록을 선언하고 실행 가능한  코드를 입력합니다.
    Line 3 $firstName 본문과 초기화 블록에서는 헤더의 프로퍼티에 접근 가능합니다.

     

    초기화 블록은 여러 번 선언될 수 있습니다. 

    class Person(firstName: String) {
        init {
            println("This first name is $firstName")
        }
    
        init {
            println("and hello world!")
        }
    }

    객체가 생성될 때 선언된 모든 초기화 블록이 실행됩니다.

    $ ./gradlew -q testConstuctor
    This first name is man
    and hello world!

    필요한 경우 프로퍼티를 선언하고 초기화하는 구문은 다음과 같이 단순화합니다.

    class Person(firstName: String = "Ann")
    코드 비고
    Line 1 firstName: String = "Ann" 프로퍼티 firstName은 Nullable하며 이 때 Ann을 할당합니다.

    프로퍼티를 선언할 때 trailing comma(,)를 사용 할 수 있습니다.

    class Person(
        val firstName: String,
        val lastName: String,
        var age: Int, // trailing comma
    ) { }

    클래스에서 어노테이션을 사용해야 하는 경우 constructor 키워드는 반드시 포함되어야 합니다.

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

    자세한 내용은 visibility modifiers를 참고합니다.

    보조 생성자(Secondary constructors)

    보조 생성자는 클래스 본문에서 constructor 키워드로 선언합니다.

    class Person(val pets: MutableList<Pet> = mutableListOf())
    
    class Pet {
        constructor(owner: Person) {
            owner.pets.add(this)
        }
    }

    클래스에 주 생성자와 보조 생성자가 동시에 선언되는 경우 보조 생성자는 주 생성자를 직접적으로 또는 간접적으로 호출해야합니다.

    class Person(val name: String) {
        val children: MutableList<Person> = mutableListOf()
        constructor(name: String, parent: Person) : this(name) {
            parent.children.add(this)
        }
    }
    코드 비고
    Line 1 Person(val name: String) 클래스의 주 생성자입니다.
    Line 3 this(name) 보조 생성자에서는 주 생성자를 호출합니다.

    초기화 블록 코드는 주 생성자가 우선 실행됩니다.

    만약 주 생성자가 선언되어 있지 않더라도 초기화 블록은 주 생성자에서 먼저 실행됩니다.

    class Person(i: Int) {
        init {
    	// this block called first
            println("Invoked primary constructor, i: $i")
        }
    
        constructor(i: Int, j: Int): this(i) {
        // this block called second
            println("Invoked secondary constructor, i: $i, j: $j")
        }
    }

    추상 클래스가 아닌 클래스가 어떤 생성자도 가지지 않으면 디폴트 생성자가 만들어집니다.

    디폴트 생성자는 프로퍼티를 갖지 않으며 public 접근자가 부여됩니다.

    디폴트 생성자의 public 엑세스를 피하려면 임의의 접근자를 지정 후 빈 생성자를 선언합니다.

    class DontCreateMe private constructor() { }
    더보기

    JVM에서 주 생성자의 프로퍼티가 모두 default 값을 갖고 있으면 컴파일러는 프로퍼티가 없는 빈 생성자를 만듭니다.

    빈 생성자를 필요로하는 Jackson 또는 JPA와 같은 라이브러리에서 Kotlin과 호환될 수 있도록 하기 위함입니다.

    class Customer(val customerName: String = "")

    객체 생성하기

    클래스로부터 객체를 생성하려면 생성자를 정규 함수처럼 사용합니다.

    class Person { }
    
    val person = Person()
    더보기

    Kotlin은 객체 생성을 위한 new 키워드를 제공하지 않습니다.

    추상 클래스와 추상 멤버

    abstract 키워드를 사용하면 추상 클래스를 선언하거나 멤버 변수 또는 멤버 함수를 추상 멤버로 만듭니다.

    추상 멤버의 경우 해당 클래스 선언부에서 구현 할 필요는 없습니다.

    abstract class Polygon {
        abstract fun draw()
    }
    
    class Rectangle : Polygon() {
        override fun draw() {
        	// somethings
        }
    }

    반대로 추상 클래스가 아닌 클래스에서 open 멤버를 추상 멤버로 상속 할 수도 있습니다.

    open class Polygon {
        open fun draw() {
            // something
        }
    }
    
    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()
    }

    정리 및 복습

    • Kotlin에서 클래스는 class 키워드로 선언합니다.
    • 생성자는 class <클래스 이름> constructor <클래스 헤더> <클래스 본문>으로 구성합니다. 
    class Person constructor(firstName: String) { }
    • constructor 키워드와 본문 블록({})은 생략 할 수 있습니다.
    • 초기화 블록은 init 키워드로 선언합니다.
    • 초기화 블록은 여러 번 선언할 수 있으며 모두 실행됩니다.
    • 객체를 생성하려면 생성자를 정규 함수 val person = Person()처럼 사용합니다.
    • 생성자는 주 생성자(Primary constructor)보조 생성자(Secondary constructor)가 있습니다.
    • 주 생성자와 보조 생성자가 동시에 선언되는 경우 보조 생성자는 주 생성자를 직접적으로 또는 간접적으로 호출해야합니다.
    • JVM에서 주 생성자의 프로퍼티가 모두 default 값을 갖고 있으면 컴파일러는 프로퍼티가 없는 빈 생성자를 만듭니다.
    • 추상 클래스 또는 추상 멤버를 선언하려면 abstract 키워드를 사용합니다.