Difference Between Abstract Class and Interface in Kotlin

1. Introduction

In Kotlin, both abstract classes and interfaces are used to define types that cannot be instantiated on their own and can be used to define methods that must be implemented by derived classes. An abstract class is a class that cannot be instantiated and can contain both abstract (without implementation) and non-abstract (with implementation) methods. An interface, however, can only contain abstract methods (until Kotlin 1.4, where default implementations were introduced) and properties but no state.

2. Key Points

1. Method Implementation: Abstract classes can have both abstract and concrete methods, interfaces only abstract methods (with default implementations allowed in Kotlin 1.4+).

2. State: Abstract classes can hold state (fields), but interfaces cannot.

3. Inheritance: A class can inherit from only one abstract class but can implement multiple interfaces.

4. Constructor: Abstract classes can have constructors, but interfaces cannot.

3. Differences

Characteristic Abstract Class Interface
Method Implementation Abstract and concrete methods Only abstract methods (default implementations allowed)
State Can hold state Cannot hold state
Inheritance Single inheritance Multiple inheritance
Constructor Can have constructors Cannot have constructors

4. Example

// Example of an Abstract Class
abstract class Vehicle {
    abstract fun start()
    fun stop() {
        println("Stopped")
    }
}

// Example of an Interface
interface Drivable {
    fun drive()
}

class Car : Vehicle(), Drivable {
    override fun start() {
        println("Car started")
    }

    override fun drive() {
        println("Car driving")
    }
}

Output:

Abstract Class Output:
Vehicle cannot be instantiated, but provides a common method stop() and an abstract method start().
Interface Output:
Drivable defines a contract with a drive() method that must be implemented.

Explanation:

1. Vehicle is an abstract class with a concrete method stop and an abstract method start. It can hold state and have constructors.

2. Drivable is an interface that only defines a behavior with the drive method, without holding any state or having constructors.

5. When to use?

- Use an abstract class when you need a base class that provides common implementations to derived classes, along with possibly maintaining state.

- Use an interface when you need to define a contract (methods) that different classes can implement, without concern about the state.

Comments