Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 134 ยท Classes and Objects

Abstract Classes

Learn Kotlin abstract classes: abstract members, constructors and state, the template method pattern, and when to choose an abstract class over an interface, with runnable code.

Sometimes you know what a family of classes must do, but not how every member of the family will do it. A Shape should be able to report its area, but the formula for a circle and the formula for a rectangle have nothing in common. An abstract class captures this: it is a class that is deliberately incomplete. It can hold state and finished code that all subclasses share, and it can declare abstract members that every concrete subclass must fill in.

You cannot create an instance of an abstract class. It exists to be extended. This lesson shows how to declare one, what it can contain, how the template method pattern uses it, and, most importantly, how to decide between an abstract class and an interface. It builds on Inheritance.

Declaring an abstract class

Put the abstract modifier in front of class. Inside, mark the members that have no body as abstract too:

Kotlin An abstract class with one abstract member

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Shape mixes two kinds of members. area() is abstract: it has no body and subclasses must implement it. describe() is a normal, finished function that calls area(). Because describe() is written once, every shape gets it for free, and each shape's own formula is used when it runs.

Two details are worth noticing:

  • An abstract member is implicitly open. You never write abstract open, because an abstract member that nobody could override would be useless.
  • The describe() function is not open. Members of any class, abstract or not, are final unless you say otherwise, so subclasses cannot change describe() by accident.

You cannot instantiate it

An abstract class is incomplete, so Kotlin refuses to build one. The compiler tells you at the exact spot:

Kotlin Instantiating an abstract class (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler reports error: cannot create an instance of an abstract class. and the program does not build. The fix is to create an instance of a subclass that implements every abstract member, or to use an anonymous object, which is a subclass written on the spot:

Kotlin Subclass or anonymous object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

A subclass that forgets an abstract member is itself incomplete, so it must also be marked abstract, or the compiler complains. That is the safety net: the abstract class is a contract, and the compiler checks that every concrete class honors it.

State and constructors

An interface cannot store state in its own fields. An abstract class can: it can have a primary constructor, properties with backing fields, init blocks, and secondary constructors, exactly like any other class. Subclasses must call one of its constructors, and its initialization runs first.

Kotlin State, init blocks and the order of construction

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The superclass runs first (Account init), then the subclass (BasicAccount init). balance has a protected set, so subclasses can change it but outside code cannot. And fee is an abstract property: abstract members can be properties as well as functions. Each subclass decides whether it is a stored value (override val fee = 2) or computed (override val fee get() = ...).

Do not call an abstract or open member from a constructor or init block of the abstract class. The subclass's own properties are not set yet, so the override would see default values (0, null). If you must, make the initialization lazy or move it to a separate start() method that runs after construction.

Here is that trap in action. The subclass override reads its own property before it has been assigned:

Kotlin Calling an abstract member from init

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The base class prints null because Derived.label has not been assigned when Base's init runs. The program compiles and runs without any complaint, which is what makes the bug easy to miss. Keep construction free of virtual calls.

The template method pattern

The most useful job for an abstract class is the template method: a finished function defines the skeleton of an algorithm, and abstract (or open) steps let subclasses fill in the details. The skeleton is fixed, so every subclass follows the same sequence, and the variable parts are small and named.

Kotlin A report generator skeleton

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice the three kinds of members. render() is final and public: the algorithm itself. header, rows and formatRow are protected abstract: subclasses must supply them, and outside code cannot call them. footer is protected open: a hook with a sensible default that subclasses may replace. This division makes the class easy to use correctly and hard to misuse.

Abstract class or interface?

Both let you define a contract that others implement, and both can contain finished code. They differ in what they can carry:

Feature Abstract class Interface
Stores state (backing fields) Yes No
Constructors and init blocks Yes No
A class can extend / implement Only one Many
Default implementations Yes Yes
Protected members Yes No (all members public)
Instances possible directly No No

The practical rules:

  • If the types you are modeling only need a capability ("can be compared", "can be drawn", "can be closed"), use an interface. A class can have many capabilities.
  • If the types share state or initialization and form one clear family, use an abstract class. Account, Shape and Report all have a core of shared fields or logic.
  • If you are unsure, start with an interface. It is easier to add an abstract class later than to untangle a class that already uses its single superclass slot.
  • When you need both, combine them: an interface for the public contract and an abstract class as a convenient base that implements part of it. The standard library does this: List is an interface and AbstractList is the helper base in the JDK.

Also compare with sealed classes. An abstract class lets anyone extend it from anywhere. A sealed class limits its subclasses to a known set, which lets when be exhaustive. Pick abstract when the family is open-ended and sealed when it is closed.

Do not use an abstract class only to share a couple of helper functions. Extension functions, top-level functions or delegation do that without burning your single inheritance slot.

Overriding and super calls

A subclass can partly reuse an inherited implementation with super. When a class inherits an implementation from an abstract class and also from an interface, qualify the call as super<Name>.member(). Calling super.member() on an abstract member is a compile error, because there is no body to run.

Kotlin Calling super and partial overrides

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You can also make an inherited non-abstract member abstract again by overriding it as abstract override in an abstract subclass, which forces further subclasses to provide it. This is rare, but occasionally useful when a base class's default is wrong for a whole branch of the hierarchy.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens if you write val s = Shape("x") where Shape is abstract?

    Abstract classes can never be instantiated directly, whatever they contain. You instantiate a concrete subclass or an anonymous object that extends it.
  2. 2. Which of these can an abstract class have that an interface cannot?

    Interfaces cannot hold state (no backing fields) and have no constructors. Abstract classes can have both.
  3. 3. In the template method pattern, which member should usually be final?

    The template method fixes the order of steps so subclasses cannot reorder or skip them. Members of a class are final by default, so you simply leave it without open.
  4. 4. A class Dog extends abstract class Animal which has abstract fun sound(): String. Dog does not override sound. What must be true?

    A concrete class must implement every inherited abstract member. Otherwise it is incomplete and must itself be declared abstract.
  5. 5. Why is calling an abstract member from the abstract base class's init block risky?

    The base class initializes before the subclass, so an override that reads subclass state sees null or zero. Avoid virtual calls during construction.

Summary

  • An abstract class cannot be instantiated; it defines a partial implementation plus abstract members that subclasses must supply.
  • Abstract members are implicitly open; ordinary members stay final unless marked open.
  • Abstract classes can hold state, constructors and init blocks; the base class initializes before the subclass.
  • Avoid calling abstract or open members during construction.
  • The template method pattern uses a final method for the skeleton and abstract or open members for the steps.
  • Choose an interface for capabilities and an abstract class for a family with shared state; use sealed for a closed family.

Next: Data Classes