Encapsulation

OOP: Encapsulation

Concept of encapsulation:

Encapsulation is a fundamental concept of object-oriented programming that allows the bundling of data (attributes) and methods (behaviors) that operate on the data into a single unit, called a class. Encapsulation helps in hiding the internal state of an object from the outside world and only exposing the necessary functionalities through methods.

Let's create and break down a program from the syntax which is provided on the OOP page:

cs Copy Code
using System;

class Person {
    private string name;

    public string Name {
        get { return name; }
        set { name = value; }
    }

    public void DisplayInfo() {
        Console.WriteLine($"Name: {Name}");
    }
}

class Program {
    static void Main(string[] args) {
        Person person = new Person();
        person.Name = "Ayn Sarkar";
        person.DisplayInfo();
    }
}

Note: In the provided program, the class 'Person' demonstrates encapsulation.

Output:
Name: Ayn Sarkar

Explanation:

1. private string name; This line declares a private field 'name', which is accessible only within the 'Person' class. It encapsulates the data related to the person's name, restricting direct access from outside the class.

2. public string Name { get { return name; } set { name = value; } } This is a property named 'Name', which provides controlled access to the private field 'name'. The 'get' accessor allows reading the value of 'name', and the 'set' accessor allows modifying the value of 'name'. This property encapsulates the access to the 'name' field, allowing controlled modification and retrieval of its value.

3. public void DisplayInfo() { Console.WriteLine($"Name: {Name}"); } This method 'DisplayInfo()' encapsulates the behavior of displaying the person's name. Instead of directly accessing the 'name' field, it uses the 'Name' property to retrieve the name value. This demonstrates encapsulation by encapsulating the behavior of displaying the person's name.

In summary, encapsulation in this context allows the 'Person' class to control access to its internal data ('name' field) through properties ('Name') and methods ('DisplayInfo()'), providing a clear interface for interacting with 'Person' objects while hiding the implementation details.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.