Skip to the content.

Class Hierarchies

Final Classes

Classes are final by default.

Open Classes

Classes designed for inheritance have to marked with open

Sealed Classes

A sealed class is open for extension by other classes defined in the same file

Interfaces

Interfaces in Kotlin supports

interface Itf {
  fun methodSignature()

  fun methodImplementation() {
    println("default method implementation")
    return methodSignature()
  }

  companion object {
    fun staticMethod(itf: Itf) = itf.methodSignature()
  }
}

Implementing an interface

class Impl: Itf {
  // explicit overrride
  override fun methodSignature() {
    println("method signature implementation")
  }
}

val instance = Impl()
instance.methodSignature()
instance.methodImplementation()
Itf.staticMethod(instance)

Abstract Classes

Can have state

abstract class AbstractType(var count: Int) {
  abstract fun abstractMethod()
}

class Impl(count: Int): AbstractType(count) {
  override fun abstractMethod() {
    println(count++)
  }
}

Nested and Inner Classes

class Outer(val count: Int) {
  val newInner: Inner
    get() = Inner()

  inner class Inner {
    // this is the Inner instance. this@Outer is the outer instance
    fun info() = "Inner $this - Outer ${this@Outer} - count ${this@Outer.count}"
  }
}

val o = Outer(42)
println(o)

val i = o.newInner
println(i)
println(i.info())