초기화

Anna·2024년 6월 11일
0

코틀린

목록 보기
18/28
post-thumbnail

클래스 내부에서 하는 초기화는 값을 할당하기 위한 초기화, main에서 하는 초기화는 할당한 값으로 초기화

초기화

1. 주 생성자를 사용한 초기화

class MyClass(val prop1: Int, val prop2: String) 
{
    // 클래스 내부에 다른 코드가 있을 수 있음
}

2. 부 생성자를 사용한 초기화

class MyClass 
{
    val prop1: Int
    val prop2: Int
    
    constructor(value1: Int, value2: Int) 
    {
        // prop1과 prop2를 초기화
        prop1 = value1
        prop2 = value2
    }
}

3. 프로퍼티 초기화 식을 사용한 초기화

class MyClass 
{
	// 클래스 인스턴스가 생성될 때 자동으로 prop1에 값 1이 할당
    val prop1: Int = 1
    val prop2: Int = 2
}

4. init() 초기화

주 생성자 혹은 부 생성자가 호출될 때, 클래스의 인스턴스가 초기화될 때 실행되는 초기화 블록이다. (생성과 동시에 실행되는 블록) (객체 생성과 비슷한 동작원리)
클래스의 초기화와 관련된 작업을 수행하기 위한 블록이지만, 모든 초기화 작업을 반드시 여기서 해야하는 것은 아니다. init블록에서 초기화되지 않은 프로퍼티는 생성자에서 직접 초기화하거나, 나중에 다른 메서드에서 초기화할 수도 있다.
주 생성자가 있을 때

class MyClass(val prop1: Int, val prop2: Int) 
{
    init 
    {
        println("prop1: $prop1, prop2: $prop2")
    }
}

fun main() 
{
    val obj = MyClass(1, 2)
    println("prop1: ${obj.prop1}, prop2: ${obj.prop2}")
}

주 생성자가 없을 때 - init()

class MyClass 
{
    val prop1: Int
    val prop2: Int

    init 
    {
        // 초기화할 값을 할당
        prop1 = 1
        prop2 = 2
        println("prop1: $prop1, prop2: $prop2")
    }
}

fun main() 
{
    val obj = MyClass()
    println("prop1: ${obj.prop1}, prop2: ${obj.prop2}")
}

주 생성자가 없을 때 - 부 생성자

class MyClass 
{
    val prop1: Int
    val prop2: Int

    constructor(value1: Int, value2: Int) 
    {
        this.prop1 = value1
        this.prop2 = value2
        println("prop1: $prop1, prop2: $prop2")
    }
}

fun main() 
{
    val obj = MyClass(1, 2)
    println("Object created with prop1: ${obj.prop1}, prop2: ${obj.prop2}")
}

상속 init()

init는 상속 관계에서도 사용할 수 있다.
부모 클래스의 init 블록은 부모 클래스의 프로퍼티 초기화에 사용될 수 있고, 자식 클래스의 init 블록은 자식 클래스의 프로퍼티 초기화에 사용될 수 있다.

0개의 댓글