코틀린

13. 클래스 - 상속

mks160615 2025. 1. 29. 17:00

객체 지향 프로그래밍에서 설명하였듯이 부모 클래스의 변수와 함수를 자녀 클래스에서 재사용하는 것을 뜻한다.

 

상속을 하는 이유는?

만약 동일한 코드를 100개의 클래스에서 사용한다고 가정하자. 그렇다면 수정할 때 어떻게 될까?

수많은 시간과 노력이 필요할 것이며 분명 오타로 인한 프로그램 에러 상황이 발생할 것이다.

이를 방지하기 위해 공통으로 사용하는 코드는 부모 클래스에서 변수나 함수로 선언해 자식 클래스에서 상속받아 사용한다.

 

open

부모 클래스에서 자녀 클래스에 코드를 물려주기(?) 위해서는 open을 선언해야 한다. open은 클래스나 함수 맨 앞에 작성한다.

open class Device(val model : String, val company : String, val price : Int){
// 부모 클래스나 함수를 open 선언해야 자식 클래스에서 사용할 수 있다.

    fun printModel() : String{
        return "Model is $model"
    }

    fun printCompany() {
        println("Company is $company")
    }

    fun printPrice(){
        println("Price is $price")
    }

    open fun printAI(){
        println("This is AI")
    }
}

 

선언된 부모의 코드를 이용하기 위해서 자식 클래스는 부모 클래스의 매개 변수를 그대로 받아 사용해야 한다.

class Samsung (model: String, company: String, price: Int) : Device(model, company, price){

}

 

override

부모 클래스에서 변수나 함수에 open을 선언하면 자식 클래스에서는 반드시 해당 객체를 재정의해야 한다.

class Samsung (model: String, company: String, price: Int) : Device(model, company, price){
    override fun printAI() {
        println("Hi Bixby")
    }
}

 

super

부모 클래스의 코드를 자식 클래스에서 사용하기 위해 사용한다.

class Samsung (model: String, company: String, price: Int) : Device(model, company, price){
    override fun printAI() {
        super.printAI() // super: 자녀 클래스에서 부모의 코드를 사용할 수 있게 해준다.
        println("Hi Bixby")
    }
}

super를 통해 "Hi Bixby"만 출력될 예정이었던 printAI() 함수는 이제 아래와 같이 출력된다.

This is AI
Hi Bixby

 

메인 함수에서는 매개 변수를 고려햐여 클래스를 선언한다.

fun main() {
    val galaxy = Samsung("Galaxy", "Samsung", 1250)
}

 

이때 변수명 뒤에 .함수 명을 작성하면 Samsung 클래스에서 선언된 함수를 사용할 수 있다.

println(galaxy.printModel()) // Model is Galaxy
galaxy.printCompany() // Company is Samsung

 

Apple 클래스를 선언한다면 클래스에 필요한 변수, 함수를 다시 작성할 수고로움은 사라진다.

class Apple (model: String, company: String, price: Int) : Device(model, company, price){
    override fun printAI() {
        super.printAI()
        println("Hey Siri")
    }
}

 

fun main() {
    val ip = Apple("iPhone", "Apple", 1500)
    ip.printPrice() // Price is 1500
    ip.printAI() // This is AI \nHey Siri
}

 

 

 

GitHub - KrillM/Kotlin_Again: init project

init project. Contribute to KrillM/Kotlin_Again development by creating an account on GitHub.

github.com

 

'코틀린' 카테고리의 다른 글

12. 클래스 - 기본  (1) 2025.01.29
11. 객체 지향 프로그래밍  (0) 2025.01.29
10. 자료 구조  (0) 2025.01.29
09. 함수  (1) 2025.01.29
08. String Template  (0) 2025.01.29