ProgrammingKotlin/Java developer

How does constructor inheritance work in Kotlin, how does the super constructor call work, and what pitfalls exist when combining primary and secondary constructors? Provide examples for different cases and explain the differences from Java.

Pass interviews with Hintsage AI assistant

Answer

In Kotlin, a class can have one primary constructor and an unlimited number of secondary constructors. The difference from Java is that in Kotlin, the primary constructor is declared in the class header and can contain parameters and modifiers. Secondary constructors must always call either another secondary constructor, the primary constructor, or the superclass constructor (using the super keyword).

Key features:

  • If the superclass has a primary constructor with mandatory parameters, the derived class always has to explicitly call it via : super(...).
  • In a secondary constructor, the base class is called via super(...) or another secondary/primary constructor.
  • Initialization conflicts are not allowed: all fields must always be properly initialized.

Example of usage with inheritance:

open class A(val a: Int) { constructor(a: Int, str: String) : this(a) { println("Secondary in A: $str") } } class B : A { constructor(a: Int) : super(a) { println("Secondary in B") } constructor(a: Int, s: String) : super(a, s) { println("Secondary #2 in B") } }

How the approach differs from Java:

  • In Kotlin, it is not possible to NOT call the superclass constructor.
  • The primary constructor always initializes base parameters and can be implicit.

Trick question

Is it possible in Kotlin to create a derived class without explicitly calling the superclass constructor, if there is only a specific constructor in the base class?

Answer: No, unlike Java, in Kotlin, calling the superclass constructor is mandatory and is explicitly specified either in the "head" of the class or after the : super() keyword.

Example of an error:

open class Base(val x: Int) class Derived : Base // Compilation error!

Examples of real errors due to lack of knowledge of the topic


Story

In a microservice project after migrating to Kotlin, they forgot to explicitly specify the parent constructor: the superclass constructor with a mandatory parameter was not called, the service did not compile, and refactoring of signatures was required.


Story

An Android project had a deep hierarchy (Activity → BaseActivity → CustomActivity), adding a secondary constructor lost parameters, leading to a call to the wrong base constructor, leaving some fields null — the application crashed at runtime with NPE.


Story

In open library code, a secondary constructor in the child class accidentally bypassed the primary constructor, leading to two different initialization branches: sometimes the field was initialized, sometimes it was not. The error was discovered only after a long time due to complex bug reports.