Inheritance

Inheritance is ability to define a new classes as extensions of an existing class. As a result, we reuse existing code and can use child classes wherever the parent class can be used.

The open keyword applied to the class allows you to inherit from that class. By default classes are final and cannot be parent to other classes.

You can specify a parent class after primary constructor.

By default parent class is Any class. In other words the Any class is superclass for all other classes in Kotlin.

open class Base(p: Int)

class Derived(p: Int) : Base(p)
class MyView : View { constructor(ctx: Context) : super(ctx) constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs) }

polymorphism

The open keyword applied to a method allows you to override the method in a child class. By default, methods are final and you cannot override them in child classes.

The override keyword is used to ensure that you are overriding a method and not defining a new method.

The final keyword allows you to prohibit re-overriding method.

The super keyword refers to the parent class. It is useful for calling parent version of method.

Same rules are applied to the properties.

open class Shape {
    open val vertexCount: Int = 0
     
    open fun draw() { /*...*/ }
    open fun fill() { /*...*/ }
}

class Circle: Shape() { 
   final override fun draw() { /*...*/ }
}

open class Rectangle(): Shape() {
    val borderColor: String get() = "black"
    override val vertexCount = 4
    override fun draw() { /*...*/ }
}

class FilledRectangle: Rectangle() {
    override fun draw() {
        super.draw()
        /*...*/
    }

    val fillColor: String get() = super.borderColor
}

You can override constant property in constructor or redefine it as a variable.

class Polygon(override val vertexCount: Int = 10): Shape() {
    // ...
}

class Polygon2: Shape() {
    override var vertexCount: Int = 10
    // ...
}