728x90

나는 C++로 상속을 배웠는데

개념적으로 너무 새롭거나 하기보다는 비슷하게느껴졌다.

 

코틀린 상속의 특징

 

1. 클래스도 메서드도 모두 상속 불가(final) 가 Default

open 을 붙여주면 상속가능

 

2. override 시 override 라고 앞에 붙여줌

 

3. 클래스 선언 시 부모클래스 뒤에 파라미터가 없으면 기본 생성자가 호출되고 파라미터를 넘길 수 도 있다.

 

 

실습해본 코드

 

Inheritance.kt

class Inheritance {
	// 1
    class Human()        // default : final 상속불가
    open class Animal(val species : String, val name : String)     // 상속가능
    {
        open fun whoAreYou() {
            println("I am $name, a $species")
        }
    }

	// 2, 3
    class Dog(name : String) : Animal(species = "Dog", name = name)

    class Cat(name: String) : Animal(species = "Cat", name = name)
    {
        override fun whoAreYou() {
            println("I am $name, a $species Meow meow")
        }
    }

}

 

Main.kt

import Inheritance

fun main() {
    val lola = Inheritance.Dog("Lola")
    lola.whoAreYou()
    val inky = Inheritance.Cat("Inky")
    inky.whoAreYou()
}

 

 

출처 : https://play.kotlinlang.org/byExample/01_introduction/07_Inheritance

728x90

+ Recent posts