Abstract class with several subclasses in Kotlin
Level 5367 keystrokes
Shape declares the abstract method area() and the concrete method describe(), which uses it. Circle and Rectangle each implement area(), so describe() gives the right result for each shape.
Kotlin code
// An abstract class cannot be instantiated directly1abstract class Shape { // Each subclass must provide area()2 abstract fun area(): Double // Shared method that calls the subclass's area()3 fun describe() = "Area: ${area()}"4}5 6class Circle(val radius: Double) : Shape() { // Circle area: 3.14159 × 5.0 × 5.0 = 78.539757 override fun area() = 3.14159 * radius * radius8}9 10class Rectangle(val w: Double, val h: Double) : Shape() { // Rectangle area: 4.0 × 3.0 = 12.011 override fun area() = w * h12}13 // The list's element type is inferred as Shape14val shapes = listOf(Circle(5.0), Rectangle(4.0, 3.0))// Prints Area: 78.53975, then Area: 12.015for (s in shapes) println(s.describe())Output
Area: 78.53975 Area: 12.0
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Kotlin code and how often they appear.
(× 15)× 15:× 7.× 5{× 4}× 4=× 4,× 3*× 3"× 2