상속, Inheritance

김건우·2023년 12월 5일

개발 공부

목록 보기
3/13
post-thumbnail

참고 : Kotlin Docs
https://kotlinlang.org/docs/inheritance.html#overriding-properties

상속

클래스 상속

  • 기본 구조
open class Base

코틀린에서 Class는 기본적으로 final로 선언되어 있어 open 키워드를 앞에 붙이지 않으면 상속이 불가능하다.

open class Base(p: Int)

class Derived(p: Int) : Base(p)

상속받을 자식클래스는 클래스 헤더 끝에 : 부모클래스를 붙여 선언한다.

  • 모든 Class는 공통의 조상 클래스Any를 가진다.

    class Example // 암시적으로 Any 상속
  • Any 클래스는 세 개의 method를 가지고 있어 모든 Class에서 사용가능하다.

    equals()

    open operator fun equals(other: Any?): Boolean
    두 개의 객체가 동등한 지 검사한다.

    hashCode()

    open fun hashCode(): Int
    객체의 해쉬코드 (객체의 메모리 주소로 만들어낸 코드) 를 반환한다.

    toString()

    open fun toString(): String  
    객체의 인스턴스가 저장된 메모리 주소를 반환한다.

메소드 overriding

  • Class의 멤버(프로퍼티)를 override하려면 open을 멤버 앞에 붙여준다.
open class Shape {						// 부모 클래스
    open fun draw() { /*...*/ }			
    fun fill() { /*...*/ }
}

class Circle() : Shape() {				// 자식 클래스
    override fun draw() { /*...*/ }
}

부모클래스 Shape을 open으로 선언해 상속가능한 클래스로 만들고, 멤버 함수인 draw() 앞에 open을 붙여 자식클래스에서 override가능하게 만든다.
부모 클래스의 fill()은 open이 없기 때문에 자식클래스에서 같은 signature(파라미터, 타입)으로 선언할 수 없다.

  • final이 붙은 class와 member에는 open키워드를 사용해도 상속과 overriding이 불가능하다.

프로퍼티 overriding

  • 메소드 overriding과 비슷하게 동작한다.
  • override 될 프로퍼티 앞에는 open, override 받을 프로퍼티 앞에 override 키워드를 적어 사용한다.
open class Shape {
    open val vertexCount: Int = 0
}

class Rectangle : Shape() {
    override val vertexCount = 4
}
  • val 프로퍼티를 var로 override할 수 있지만, 반대는 불가능하다.
  • 주 생성자의 프로퍼티 선언 부에도 override 키워드를 사용할 수 있다.
interface Shape {
    val vertexCount: Int
}

class Rectangle(override val vertexCount: Int = 4) : Shape // Always has 4 vertices

class Polygon : Shape {
    override var vertexCount: Int = 0  // Can be set to any number later
}

super 키워드로 부모클래스 요소 사용

  • 자식클래스는 super 키워드로 부모클래스의 함수와 프로퍼티 접근자(get,set)를 사용할 수 있다.
open class Rectangle {
    open fun draw() { println("Drawing a rectangle") } 
    val borderColor: String get() = "black"
}

class FilledRectangle : Rectangle() {
    override fun draw() {						// draw()를 override
        super.draw()							// 부모클래스의 draw()사용
        println("Filling the rectangle")		// print문 추가
    }

    val fillColor: String get() = super.borderColor		// 부모클래스의 프로퍼티에 접근
}

open으로 선언한 부모클래스의 draw() 내용을 자식클래스에서 override한다.
자식클래스에서 super.draw()를 사용해 부모클래스 draw() 내용인 print문을 그대로 사용한다.
자식클래스에서 super.borderColor로 부모클래스의 프로퍼티 접근자를 사용할 수 있다.

profile
즐겁게

0개의 댓글