Lesson 3
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.

Kotlin
1class Player(var health: Int, var armor: Int, var stamina: Int) { 2 3 fun receiveDamage(damage: Int) { 4 health -= damage // Reduce health 5 } 6 7 fun shieldHit(armorLost: Int) { 8 armor -= armorLost // Decrease armor 9 } 10 11 fun restoreHealth(healthIncrease: Int) { 12 health += healthIncrease // Restore health 13 } 14} 15 16fun main(){ 17 val player = Player(100, 50, 77) 18}

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.

Kotlin
1class BankAccount(private val accountNumber: Int, private var balance: Double) { 2 3 fun deposit(amount: Double) { 4 balance += amount // Deposit money 5 } 6 7 fun getBalance(): Double { 8 return balance // Return current balance 9 } 10} 11 12fun main(){ 13 val bankAccount = BankAccount(1234, 100.0) 14 bankAccount.deposit(100.0) 15 println(bankAccount.getBalance()) // 200.0 16 // bankAccount.balance // Error: Cannot access 'balance': it is private in 'BankAccount' 17}

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.

Private Methods

Similar to private properties, private methods are accessible only within their class. Here's an example in Kotlin:

Kotlin
1class BankAccount(private val accountNumber: Int, private var balance: Double) { 2 3 // Private method 4 private fun addInterest(interestRate: Double) { 5 balance += balance * interestRate // Calculate interest 6 } 7 8 // Public method calling the private method 9 fun addYearlyInterest() { 10 addInterest(0.02) // Adds 2% interest 11 } 12} 13 14fun main(){ 15 val bankAccount = BankAccount(1234, 100.0) 16 bankAccount.addYearlyInterest() // Works for public methods 17 // bankAccount.addInterest(0.1) // Error: Cannot access 'addInterest': it is private in 'BankAccount' 18}

In this example, addInterest is a private method, meaning it can be called only within the class itself. The class method addYearlyInterest calls addInterest, but addInterest cannot be called from outside the class. This ensures controlled access to certain operations, maintaining encapsulation and integrity within the class.

Lesson Summary and Practice

Great work understanding the encapsulation, private properties, and private methods concepts in Kotlin! Mastering these foundational principles of OOP improves your code's security, usability, and robustness.

Exciting exercises are up next to reinforce your understanding. Keep practicing, and enjoy the journey of coding in Kotlin!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.