본문 바로가기

Study/Kotlin Study

[Kotlin] 추상 클래스와 추상 멤버

+ 항공대학교 김철기 교수님의 객체 지향 프로그래밍 과목 내용를 정리한 글입니다.

추상 클래스와 추상 멤버

추상 클래스: 직접 인스턴스화 할 수 없고, 다른 클래스의 상위 클래스 역할만 할 수 있는 클래스이다

abstract class Entity(val name: String)

class Person(name: String, val age: Int) : Entity(name)

fun main() {
    // val entity = Entity("Unknown") // error

    val entity: Entity = Person("John", 32) // OK
}

추상 클래스의 생성자

추상 클래스의 생성자는 하위 클래스의 위임 호출로만 호출 가능하다.

abstract class Entity(val name: String)

class Person : Entity {
    constructor(name: String) : super(name)
    constructor(firstName: String, familyName: String) : super("$firstName $familyName")
}

fun main() {
    val entity: Entity = Person("SangSin", "Park") // OK
    print(entity.name)
}

추상 멤버

추상 멤버는 타입, 파라미터 반환 타입만으로 기본적인 모습을 선언만 하고 세부 구현이 없이 상속으로 세부 구현을 정하는 멤버이다.

 

+ 추상 클래스의 모든 멤버가 추상 멤버일 필요는 없다.

 

< 추상 멤버에 대한 제약 >

1. 추상 프로퍼티는 초기화할 수 없다.

2. 추상 함수에는 본문이 없다.

3. 추상 프로퍼티와 함수 모두 명시적 타입 / 반환 타입이 필요하다.

4. 추상 멤버는 기본적으로 open이다.

import kotlin.math.PI

abstract  class Shape {
    abstract val width: Double
    abstract val height: Double
    abstract fun area(): Double
}

class Circle(val radius: Double) : Shape() {
    override val width: Double
        get() = radius
    override val height: Double
        get() = radius * 2
    override fun area(): Double = PI * radius * radius
}

class Rectangle(override val width: Double, override val height: Double) : Shape() {
    override fun area(): Double = width * height
}
fun main() {
    val circle: Shape = Circle(1.0)
    println(circle.area())
    val rectangle: Shape = Rectangle(1.0, 2.0)
    println(rectangle.area())
}

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

[Kotlin] enum 클래스  (1) 2023.11.13
[Kotlin] 인터페이스  (3) 2023.11.02
[Kotlin] 공통 메소드  (1) 2023.10.23
[Kotlin] 타입 검사와 캐스팅  (2) 2023.10.23
[Kotlin] 하위 클래스 초기화  (0) 2023.10.23