Abstract class in Kotlin

Level 4198 keystrokes

An abstract class cannot be instantiated and can mix abstract methods (no body) with concrete ones. Circle implements area(), and the inherited describe() calls it: 3.14 × 5.0 × 5.0 = 78.5.

Kotlin code

// abstract: Shape cannot be created directly, only subclassed
1abstract class Shape {
// Abstract method without a body: every subclass must implement it
2 abstract fun area(): Double
// Concrete method shared by subclasses; it calls the subclass's area()
3 fun describe() = println("Area: ${area()}")
4}
5
// Circle extends Shape; Shape() calls the superclass constructor
6class Circle(val r: Double) : Shape() {
// Implements area() with π approximated as 3.14
7 override fun area() = 3.14 * r * r
8}
9
// 3.14 × 5.0 × 5.0 = 78.5: prints Area: 78.5
10Circle(5.0).describe()

Output

Area: 78.5
Practice typing this code

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.

  • (× 9
  • )× 9
  • :× 4
  • .× 3
  • {× 3
  • }× 3
  • "× 2
  • *× 2
  • =× 2
  • $× 1

More Kotlin examples at level 4

← Kotlin typing practice