코틀린에서 추상 클래스는 abstract 키워드를 사용해 정의한다.
추상 클래스는 인스턴스화 할 수 없으며 하위 클래스에 의해 상속될 수 있다.
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 * 2
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 shape: Shape = Circle(1.0)
println(shape.area())
val shape2: Shape = Rectangle(1.0, 2.0)
println(shape2.area())
}
만약 어떤 클래스가 추상 클래스를 상속한다면 반드시 해당 추상 클래스의 추상 멤버들을 모두 초기화해야한다.
다음은 추상 클래스의 특징이다.
open이며 상속 가능하다. -> 상속이 불가능하다면 구체화 할 수 없기 때문