Topic Overview and Actualization

Welcome to an adventure into Kotlin's Abstract Classes, Interfaces, and Companion Objects. These elements are widely used in Kotlin's Object-Oriented Programming and allow for flexible code structures, much like blueprints for real-world entities.

Diving Into Abstract Classes

Think of an abstract class as a "generic" real-world category - for instance, a vehicle. We have different types of vehicles, such as cars, trucks, and bikes, that share common characteristics. We can represent these common features in an abstract class called Vehicle. Abstract classes are templates for other classes. They cannot be instantiated on their own, which means you cannot create an object of an abstract class. Instead, they must be subclassed by other "concrete" classes which then provide implementations for the abstract members.

Kotlin
abstract class Vehicle {
    abstract var color: String
    abstract fun move()
    fun description() = "This is a vehicle of color $color."
}

The abstract class Vehicle defines common functionality through abstract members, such as the move() function and color property, while also supporting concrete methods like description(). Any class deriving from Vehicle is required to implement these abstract members. Failing to implement all abstract members in a derived concrete class triggers a compilation error.

class Car : Vehicle() {
    override var color: String = "Red"
    override fun move() {
        println("The car is moving")
    }
}

class Truck : Vehicle() {
    override var color: String = "Blue"
    override fun move() {
        println("The truck is moving")
    }
}

fun main() {
    // val vehicle = Vehicle() // You cannot create an instance of an abstract class
    
    val car = Car()
    println(car.description()) // Prints: "This is a vehicle of color Red"
    car.move() // Prints: "The car is moving"
    
    val truck = Truck()
    println(truck.description()) // Prints: "This is a vehicle of color Blue"
    truck.move() // Prints: "The truck is moving"
}

The Car and Truck classes implement the abstract move() function and the color property, providing specific details that were abstract in the Vehicle class. By providing these concrete implementations, both Car and Truck become specific types of Vehicle, each with their own unique behavior and properties, demonstrating how abstract classes can be used to model a hierarchy of related classes with shared characteristics.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal