Introduction

Welcome! Today's subject is Encapsulation, a cornerstone of Object-Oriented Programming (OOP). Encapsulation bundles data and the operations that we perform on them into one unit, namely, an object. It guards data against unwanted alterations, ensuring the creation of robust and maintainable software.

Prepare yourself for an exciting journey as we delve into how encapsulation works in Kotlin and explore the vital role it plays in data privacy.

Classes Without Encapsulation

Starting with the basics, encapsulation is similar to packing data and the methods that modify this data into a single compartment known as a class. It safeguards the data in an object from external interference.

To illustrate, consider a Kotlin class representing a bank account. Without encapsulation, the account balance could be directly altered. With encapsulation, however, the balance can only change through specified methods, like depositing or withdrawing.

Let's understand the problem with the code above. The balance property is public, allowing direct access and modification. This unrestricted access can lead to errors or security vulnerabilities. For instance, a negative balance could be set, which is undesirable. Encapsulation resolves this issue by restricting direct access to the balance property. Let's see how.

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