Kotlin Inheritance Interfaces


Kotlin 상속과 인터페이스 (Inheritance and Interfaces in Kotlin)

상속 (Inheritance)

Kotlin에서 상속은 open 키워드를 사용하여 선언된 클래스를 기반으로 합니다. 기본적으로 Kotlin 클래스는 상속이 금지되어 있으며, 상속을 허용하려면 open 키워드를 사용해야 합니다.

기본 상속 예제:

open class Animal(val species: String) {
    open fun makeSound() {
        println("Animal makes a sound.")
    }
}

class Dog(species: String) : Animal(species) {
    override fun makeSound() {
        println("Dog barks.")
    }
}

fun main() {
    val myDog = Dog("Canine")
    myDog.makeSound()  // 출력: Dog barks.
}

Animal 클래스는 open 키워드로 상속이 가능하게 선언되었으며, makeSound 메서드도 open 키워드를 사용하여 하위 클래스에서 재정의할 수 있습니다. Dog 클래스는 Animal 클래스를 상속받아 makeSound 메서드를 재정의합니다.

추상 클래스 (Abstract Classes)

Kotlin에서 추상 클래스는 abstract 키워드를 사용하여 선언되며, 추상 클래스는 직접 인스턴스를 만들 수 없습니다. 추상 클래스는 추상 메서드를 포함할 수 있으며, 하위 클래스는 추상 메서드를 구현해야 합니다.

추상 클래스 예제:

abstract class Animal(val species: String) {
    abstract fun makeSound()

    fun showSpecies() {
        println("Species: $species")
    }
}

class Cat(species: String) : Animal(species) {
    override fun makeSound() {
        println("Cat meows.")
    }
}

fun main() {
    val myCat = Cat("Feline")
    myCat.makeSound()  // 출력: Cat meows.
    myCat.showSpecies()  // 출력: Species: Feline
}

Animal 추상 클래스는 makeSound 추상 메서드를 포함하며, 하위 클래스인 Cat은 이 메서드를 구현해야 합니다.

인터페이스 (Interfaces)

Kotlin에서 인터페이스는 interface 키워드를 사용하여 선언됩니다. 인터페이스는 메서드 선언과 구현을 모두 포함할 수 있으며, 다중 상속이 가능합니다.

인터페이스 예제:

interface Drivable {
    fun drive()
}

interface Flyable {
    fun fly()
}

class FlyingCar : Drivable, Flyable {
    override fun drive() {
        println("Driving on the road.")
    }

    override fun fly() {
        println("Flying in the sky.")
    }
}

fun main() {
    val myFlyingCar = FlyingCar()
    myFlyingCar.drive()  // 출력: Driving on the road.
    myFlyingCar.fly()  // 출력: Flying in the sky.
}

FlyingCar 클래스는 DrivableFlyable 인터페이스를 구현하며, 각각의 메서드를 재정의합니다.

인터페이스 상속 (Interface Inheritance)

인터페이스도 다른 인터페이스를 상속받을 수 있습니다. 상속받은 인터페이스의 메서드는 구현 클래스에서 재정의해야 합니다.

인터페이스 상속 예제:

interface Animal {
    fun makeSound()
}

interface Pet : Animal {
    fun play()
}

class Dog : Pet {
    override fun makeSound() {
        println("Dog barks.")
    }

    override fun play() {
        println("Dog plays with a ball.")
    }
}

fun main() {
    val myDog = Dog()
    myDog.makeSound()  // 출력: Dog barks.
    myDog.play()  // 출력: Dog plays with a ball.
}

Pet 인터페이스는 Animal 인터페이스를 상속받아 makeSoundplay 메서드를 선언하며, Dog 클래스는 이 두 메서드를 모두 구현합니다.

Kotlin의 상속과 인터페이스를 이해하면 객체지향 프로그래밍의 개념을 더욱 잘 활용할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *