Kotlin: why use Abstract classes (vs. interfaces)?

Answer #1 100 %

The practical side of abstract classes is that you can encapsulate a part of implementation that works with the state, so that it cannot be overridden in the derived classes.

In an interface, you can only define a property without a backing field, and an implementation class must override that property (with either a backing field or custom accessors).

Given that, you cannot define logic that stores some state in an interface in a reliable way: an implementation class might override the properties in an unexpected way.


interface MyContainer {
    var size: Int

    fun add(item: MyItem) { 
        // ...
        size = size + 1

Here, we provide a default implementation for add that increments size. But it might break if an implementing class is defined like this:

class MyContainerImpl : MyContainer {
    override val size: Int 
        get() = 0
        set(value) { println("Just ignoring the $value") }

On contrary, abstract classes support this use case and thus allow you to provide some guarantees and contract for all their implementations: they can define some state and its transitions that will stay the same in a derived class.

Apart from that, abstract classes can have non-public API (internal, protected) and final members, whereas interfaces cannot (they can only have private members, which can be used in the default implementations), and all their default implementations can be overridden in the classes.

You’ll also like:

© 2023 CodeForDev.com -