세상은 모험을 두려워 하지않은 자의 것이다~~!

Java 개발자가 Kotlin 을 공부하면서.. 끄적인 노트입니다.

 

상속 (Inheritance)

/**
 * 코틀린에도 Java 처럼 상속 개념이 있다.
 * 코틀린은 클래스와 함수가 기본적으로 final 이다, 클래스를 상속받고, 재정의 하려면 open 키워드를 사용해야한다.
 */
open class Car {

    var wheelSize: Int = 20;
    open var color: String = "White"
    open var doorCount: Int = 4;

    open fun carInfoPrint() {
        println("내차는 ${color}이다.")
    }

    fun upgradeWheelSize() {
        wheelSize += 1
    }
}

class SportsCar : Car() { // 클래스 명뒤에 콜론 뒤에 Car 생성자를 호출함으로써 상속받았음을 의미한다.
    override var color = "Silver"
    //    override wheelSize = 30 // wheelSize는 open 속성이 아니라 재정의 불가
    override var doorCount = 2

    override fun carInfoPrint() {
        println("SportsCar는 문짝이 ${doorCount} 이고 ${color} 색상이다. 많은 차들은 문짝이 ${super.doorCount} 이고, ${super.color} 색상이다.")
    }

//    override fun upgradeWheelSize() {} // open 함수가 아니라 재정의 불가
}

fun testOverride() {
    SportsCar().carInfoPrint()
    // SportsCar는 문짝이 2 이고 Silver 색상이다. 많은 차들은 문짝이 4 이고, White 색상이다.
}


open class Car1 {
    val color: String
    val doorCnt: Int

    constructor(color: String, doorCnt: Int) {
        this.color = color
        this.doorCnt = doorCnt
    }

    open fun carInfoPrint() {
        println(" 문짝이 ${doorCnt}개 이고, ${color} 색상이다.")
    }
}

/**
 * Primary Constructor (기본생성자) 로 정의 할 수 있고
 */
class SportUtilityVehicle(color: String, doorCnt: Int) : Car1(color, doorCnt) {
    override fun carInfoPrint() {
        println("SUV 문짝이 ${doorCnt}개 이고, ${color} 색상이다.")
    }
}

/**
 * Secondary Constructor (보조 생성자) 로 정의 할 수 있다.
 */
class SportUtilityVehicle1 : Car1 {
    var foldingChair: Boolean

    constructor(color: String, doorCnt: Int, foldingChair: Boolean) : super(color, doorCnt) {
        this.foldingChair = foldingChair
    }

    override fun carInfoPrint() {
        println("SUV 문짝이 ${doorCnt}개 이고, ${color} 색상이고 의자가 ${if (foldingChair) "접힌다." else "안접힌다."}")
    }

    open class InnerClass {
        open fun wow(){
            println("WOW")
        }
    }

    fun anonymousTest(){
        // Anonymous Class 는 Java 와 다르게 object 키워드를 명시적으로 붙여줘야 한다.
        var overrodeWow = object : InnerClass() {
            override fun wow() {
                println("Anonymouse Class에서 재정의 되었음")
            }
        }
        overrodeWow.wow()
    }
}

fun testOverride1() {
    SportUtilityVehicle("Red", 5).carInfoPrint()
    // SUV 문짝이 5개 이고, Red 색상이다.
    SportUtilityVehicle1("Red", 5, true).carInfoPrint()
    // SUV 문짝이 5개 이고, Red 색상이고 의자가 접힌다.
    SportUtilityVehicle1.InnerClass().wow()
    // WOW
    SportUtilityVehicle1("Red", 5, true).anonymousTest()
    // Anonymouse Class에서 재정의 되었음
}


fun main(arr: Array<String>) {
    testOverride()
    testOverride1()
}