Encapsulation and Access Control in Object-Oriented Programming

Lesson Overview

Hello! In this lesson, we're revisiting Encapsulation, Private Properties, and Private Methods in Object-Oriented Programming (OOP). Think of encapsulation as a protective barrier, safeguarding your data and methods inside a class, much like a garden enclosed to protect its precious plants. Within this garden, some elements, such as private properties and methods, are reserved only for internal use, making your classes more secure and robust!

Into the Encapsulation

Encapsulation in OOP involves bundling data and methods within a class. This approach not only organizes the code but also enhances its security. For instance, in a multiplayer game, you may define a Player class encapsulating properties like health, armor, stamina, and methods such as receiveDamage, shieldHit, and restoreHealth.

class Player(var health: Int, var armor: Int, var stamina: Int) {
    
    fun receiveDamage(damage: Int) {
        health -= damage  // Reduce health
    }

    fun shieldHit(armorLost: Int) {
        armor -= armorLost  // Decrease armor
    }

    fun restoreHealth(healthIncrease: Int) {
        health += healthIncrease  // Restore health
    }
}

fun main(){
    val player = Player(100, 50, 77)
}

Here, player is an instance of the Player class, where you can call various methods on it.

Private Properties

In Kotlin, private properties are accessible only within their class, thereby limiting outside interference. For example, consider a BankAccount class with a private balance property, which is modifiable only through specific class methods like deposits or withdrawals.

class BankAccount(private val accountNumber: Int, private var balance: Double) {

    fun deposit(amount: Double) {
        balance += amount  // Deposit money
    }
    
    fun getBalance(): Double {
        return balance  // Return current balance
    }
}

fun main(){
    val bankAccount = BankAccount(1234, 100.0)
    bankAccount.deposit(100.0)
    println(bankAccount.getBalance()) // 200.0     
    // bankAccount.balance  // Error: Cannot access 'balance': it is private in 'BankAccount'
}

Here, balance is a private property, ensuring the secure handling of the account balance. The private keyword restricts direct access to this property from outside the class. Although we can access the balance through the getBalance method, encapsulation dictates that direct access to the property itself is restricted. This means the class maintains control over how the balance is accessed or modified, allowing for validations or additional logic to be implemented within the method if needed.

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