[kotlin] 추상 클래스에서 추상 메서드를 포함한 다양한 멤버 활용
추상 클래스는 추상 메서드를 포함하며, 해당 메서드를 상속 받는 하위 클래스에서 구현해야 합니다. Kotlin에서는 추상 클래스를 선언할 때 abstract
키워드를 사용하고, 추상 메서드는 abstract
키워드를 붙여 선언합니다.
다음은 추상 클래스와 추상 메서드의 활용 예시입니다.
추상 클래스 선언
abstract class Shape {
abstract fun calculateArea(): Double
fun display() {
println("Shape display")
}
}
위의 예시에서 Shape
클래스는 calculateArea
메서드와 display
메서드를 포함하고 있습니다. calculateArea
는 추상 메서드로, 하위 클래스에서 구현해야 합니다. display
는 일반 메서드로, 하위 클래스에서 구현하지 않아도 됩니다.
추상 클래스 활용
다음은 추상 클래스를 상속받는 하위 클래스의 예시입니다.
class Circle(private val radius: Double) : Shape() {
override fun calculateArea(): Double {
return Math.PI * radius * radius
}
}
class Rectangle(private val width: Double, private val height: Double) : Shape() {
override fun calculateArea(): Double {
return width * height
}
}
위의 예시에서 Circle
와 Rectangle
클래스는 Shape
클래스를 상속받고 있으며, calculateArea
메서드를 구현하고 있습니다.
이처럼, 추상 클래스와 추상 메서드를 활용하여 다양한 멤버를 정의하고, 이를 상속받는 클래스에서 유연하게 구현할 수 있습니다.