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.

Private Methods

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

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!

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