In Kotlin, class can have primary constructor and secondary constructor. Constructors in subclass varies according to their circumstances.
Pattern
- Subclass has no constructor
-
1class Sample: Base()
Add bracket and argument after the base class.
- Subclass has only primary constructor
-
1class Sample(): Base()
- Subclass has only secondary constructor
-
123class Sample: Base {constructor(): super() { }}
Don’t write bracket or argument after base class, and secondary constructor must delegate to constructor of the base class.
- Subclass has primary and secondary constructors
-
123class Sample(): Base() {constructor(x: Int): this() { }}
Subclass secondary constructor must delegate its constructor.
Un-inheritable class
If base class primary constructor is private
and it has no secondary constructor, then it is not inheritable. (I haven’t found the way to inherit yet.)