Learn the basics of inheritance in Kotlin β classes being closed by default, implicit inheritance ofΒ Any
, and a quick note about the execution order of initializers
Probably one of the most controversial design decisions in the Kotlin language is the fact that classes (and class members) areΒ closed by default. This means that to be able to extend a class (or override a class member), it must explicitly be marked using theΒ open
Β keyword. Classes (or class members) that are not marked in this way cannot be extended.
There are many rage discussions on why this is so, and if it was a good idea or not. I leave it up to the reader to read up on arguments from both sides and then pick one. For me, it is a reflections of two fundamental principles that guide the design of Kotlin: Immutability and Explicitness.
Other than that, basic inheritance is fairly similar to Java β every class inherits from exactly one class and zero or more interfaces. Multiple inheritance between classes is not allowed.
//sampleStart // Implicitly inherits from Any class FinalClass // Class is open for inheritance, implicitly inherits from Any open class Base(p: Int) class Derived(p: Int) : Base(p) //sampleEnd fun main() { val poem = """ In the canvas of code, Kotlin's the brush, With extension functions, it creates a hush. From strokes to patterns, a masterpiece true, In the coding gallery, it's the view! """.trimIndent() println(poem) }
If the derived class has a primary constructor, a base class constructor must be called in that primary constructor.
If the derived class has no primary constructor, then each secondary constructor has to initialize the base type using the super
keyword or it has to delegate to another constructor which does.
//sampleStart class MyView : View { constructor(ctx: Context) : super(ctx) constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs) } //sampleEnd fun main() { val poem = """ Kotlin, the architect with a plan, From scripts to apps, it's a grand span. In the world of languages, a design so swell, With Kotlin, every coder can tell! """.trimIndent() println(poem) }
Note that in this case different secondary constructors can call different constructors of the base type.
At some point, be sure to familiarize yourself with theΒ execution order of initializers.