Topic Overview and Actualization

Hello! Today, we'll reinforce our understanding of Object-Oriented Programming (OOP) in Kotlin by revisiting the concepts of Encapsulation, Abstraction, Inheritance, and Polymorphism. Let's dive in!

Revisiting the Fundamentals

We'll delve back into OOP. As you may recall, we create objects from classes, which define properties (data) and methods (operations). Also, keep in mind that the keyword this refers to the object whose methods and properties are being accessed.

Here's a refresher:

class Person {
    var name: String = ""
    fun introduce() {
        // Implicitly, "this" references the "name" of the current Person object.
        println("Hello, my name is $name.")
    }
}
Exploring the Four OOP Principles

Now, let's revisit the core principles of OOP: Encapsulation, Abstraction, Inheritance, and Polymorphism.

Encapsulation protects data by making properties private and providing safe methods for access.

Abstraction simplifies systems by creating higher-level representations.

Inheritance allows classes to share properties and methods, promoting code reusability.

Polymorphism enables different types of objects to be handled uniformly if they share some features.

Below is an example demonstrating polymorphism and inheritance:

open class Animal {
    open fun makeSound() {
        println("The animal makes a sound")
    }
}

class Pig : Animal() {
    override fun makeSound() {
        println("Oink! Oink!")
    }
}

In this example, Pig, a subclass of Animal, overrides the makeSound method, showcasing polymorphism.

Practical Examples

To solidify our understanding, let's examine some practical Kotlin examples.

First, an Employee class showcases encapsulation:

class Employee(private var name: String, private var salary: Double) {
    fun getName(): String {
        // getName provides safe access to the name property
        return name
    }

    fun getSalary(): Double {
        // Similarly, getSalary provides safe access to the salary property
        return salary
    }

    fun raiseSalary(percent: Double) {
        if (percent > 0) {
            // We can safely modify the private salary property within the class
            salary += salary * percent / 100.0
        }
    }
}

An interface is used to illustrate abstraction:

interface Drawable {
    fun draw()
}

class Circle(private val radius: Double) : Drawable {
    override fun draw() {
        // Circle implements the abstract requirement of the Drawable interface
        println("Drawing a Circle with a radius of $radius")
    }
}
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