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