OOP principles in Kotlin

Runtime, build and Gradle Junior Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Pick the fix

A team has BaseActivity → BaseNetworkActivity → BaseListActivity → FeedActivity, and changes in the base classes keep breaking screens. Better design?

Options
Hint 1 of 1

Is inheritance the only way to share behaviour?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Compose behaviour from small helpers and delegates instead of a deep hierarchy

Correct. Composition keeps each piece separate and replaceable.

Why not the others?
  • B Add another base class. Makes it deeper.
  • C Make every method open. More ways to break.
  • D Copy the code into each Activity. Duplication, not design.

30-second answer

Encapsulation hides state behind an API, such as a private val _state exposed as read-only StateFlow. Inheritance reuses behaviour from a parent class, which Kotlin makes opt-in with open. Polymorphism lets callers use one type for many implementations, such as a Repository interface with fake and real versions. Abstraction exposes what a thing does, not how.

Practise saying it · 30 s. No recording, just a timer

Explain the four OOP principles.

Say your answer out loud, then check which of these points you covered:

  • Encapsulation with private state
  • Inheritance is opt-in
  • Polymorphism via interfaces
  • Abstraction
  • Prefer composition

Deep dive

Kotlin classes are final by default to discourage fragile inheritance.

Prefer composition and delegation (by) to deep hierarchies.

Sealed types give closed polymorphism that when checks exhaustively.

Interfaces with default methods cover many cases abstract classes used to.

Common mistakes

  • Deep inheritance trees for UI screens.
  • Exposing mutable state publicly.
  • Reciting definitions without examples.

Senior take & follow-ups

One example per principle from real Android code.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why are Kotlin classes final by default?

    Show hint

    To make inheritance a deliberate choice.

  2. What's composition over inheritance?

    Show hint

    Build behaviour from smaller objects instead of extending a base class.

Similar on iOS: Protocols vs abstract classes Swift leans on protocols and value types more than class hierarchies.

Suggest a fix if something here is wrong or out of date.