본문 바로가기
Language/Kotlin

[Kotlin] 상속

by 진꿈청 2024. 9. 3.

Kotlin

 

상속

상속은 상위 클래스에 중복되는 로직을 구현하고 이를 재사용하는 것을 말한다.

상속의 관계를 흔히 `부모-자식` 클래스라고 부르며 `Is-a` 관계라고도 부른다.

 

ex. Person(parent) - Student(child)

 

 

코틀린의 상속

코틀린에서는 모든 클래스가 `Any`를 상속 받고 있는 구조이다.

`Any`에는 `equals()`, `hashCode()`, `toString()`이 구현되어 있다.

 

public open class Any{
	
    public open operator fun equals(other: Any?): Boolean
    
    public open fun hashCode(): Int
    
    public open fun toString(): String
}

 

 

부모 클래스는 `open` 키워드를 사용해 상속을 허용할 수 있다.

open class Car(val name: String, val price: Double, val brand: String){
    fun introduce(){
    	println("this car is $name, this is made by $brand.")
    }
    
    fun howMuch(){
    	println("this car is $price dollars")
    }
}

 

 

메소드 또한 오버라이드할 수 있게 `open` 키워드를 사용할 수 있다.

open class Car(val name: String, val price: Double, val brand: String){
    open fun myPurchaseDate(){
    	println("you don't buy yet")
    }
}

 

 

상속을 받는 자식 클래스는 아래와 같은 형식으로 상속을 받는다.

class MyCar(name: String, price: Double, brand: String, val purchaseDate: LocalDate) : Car(name, price, brand){

}

 

 

메소드 오버라이드는 아래와 같이 구현한다.

class MyCar(name: String, price: Double, brand: String, val purchaseDate: LocalDate) : Car(name, price, brand){
    override fun myPurchaseDate(){
    	println("you made a purchase on $purchaseDate")
    }
}

 

 

실습

Car

open class Car(val name: String, val price: Double, val brand: String) {
    fun introduce(){
        println("this car is $name. this is made by $brand.")
    }

    fun howMuch(){
        println("this car is $price dollars")
    }

    open fun myPurchaseDate(){
        println("you don't buy yet")
    }

    open fun compare(otherCar: Car) {
        println("### comparison between ${this.name} and ${otherCar.name} ###")

        println("### Price ###")
        if (this.price > otherCar.price) {
            println("${this.name} is more expensive than ${otherCar.name}")
        } else {
            println("${otherCar.name} is more expensive than ${this.name}")
        }
        println(">>> ${this.name} is ${this.price} dollars")
        println(">>> ${otherCar.name} is ${otherCar.price} dollars")

        println("### Brand ###")
        if (this.brand == otherCar.brand) {
            println("both of ${this.name} and ${otherCar.name} are same brand '${this.brand}'")
        } else {
            println(">>> ${this.name} is made by ${this.brand}")
            println(">>> ${otherCar.name} is made by ${otherCar.brand}")
        }
    }
}

 

 

MyCar

package inheritance

import java.time.LocalDate

class MyCar(name: String, price: Double, brand: String, private val purchaseDate: LocalDate) :
    Car(name, price, brand){
    override fun myPurchaseDate() {
        println("you mad a purchase on $purchaseDate")
    }
}

 

InheritanceSample

package inheritance

import java.time.LocalDate

fun main() {
    val gv70 = MyCar("GV70", 80.50, "Hyundai", LocalDate.now().minusDays(5))
    val gv80 = MyCar("GV80", 100.50, "Hyundai", LocalDate.now())

    gv70.introduce()
    gv70.howMuch()
    gv70.myPurchaseDate()

    println("======")
    gv80.introduce()
    gv80.howMuch()
    gv80.myPurchaseDate()

    println("======")
    gv80.compare(gv70)
}

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

[Kotlin] Enum Class & Data Class  (1) 2024.09.03
[Kotlin] 클래스  (0) 2024.09.02
[Kotlin] 함수  (0) 2024.09.02
[Kotlin] 조건문과 반복문  (0) 2024.09.02
[Kotlin] 연산자  (0) 2024.09.02