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 and explore the vital role it plays in data privacy.

Unraveling 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 C# 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.

public class BankAccount
{
    public double Balance; // no encapsulation

    // Method to withdraw
    public void Withdraw(double amount)
    {
        this.Balance -= amount;
    }

    // Method to deposit
    public void Deposit(double amount)
    {
        this.Balance += amount;
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        BankAccount account = new BankAccount();
        account.Balance += 1000; // directly accessing the balance
    }
}
Encapsulation: Guardian of Data Privacy

Encapsulation restricts direct access to an object's data and prevents unwanted data alteration. This principle is comparable to window blinds, allowing you to look out while preventing others from peeping in.

In encapsulation, private and public attributes are integral to data privacy. Private attributes, indicated by the private keyword, require caution while being manipulated.

To illustrate, let's consider a C# class named Person, which includes a private attribute Name.

public class Person
{
    // Private attribute
    private string name;

    // Constructor
    public Person(string name)
    {
        this.name = name;
    }

    // Accessor method
    public string GetName()
    {
        return this.name;
    }

    public static void Main(string[] args)
    {
        Person person = new Person("Alice");
        System.Console.WriteLine(person.GetName());  // Accessing private attribute via accessor method. Output: Alice
        // The following line would cause an error due to private access:
        // System.Console.WriteLine(person.name);
    }
}

In this example, name is private, and GetName() enables us to access name. However, we don't provide a method to change the name, preventing alterations.

To designate an attribute as private, we use the private keyword.

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