# Tags
#education

What is Encapsulation in OOPS Explained with Examples

What is Encapsulation in OOPS Explained with Examples

Object-oriented programming (OOP) is a way of designing and organizing software using objects and classes. A class is like a blueprint or template for creating objects, while an object is an instance of that class with specific data and behaviors. Think of a class as a plan, and an object as the actual product made from that plan. Each object has its own unique attributes and actions, and the class defines what those attributes and actions should be. When you interact with an object, you’re calling one of its methods to perform a specific action or calculation.

One of the key features of OOP is encapsulation, which helps make programming more efficient and organized. Encapsulation, along with other principles like inheritance, abstraction, and polymorphism, forms the core foundation of object-oriented programming.

Encapsulation focuses on keeping the data (attributes) of an object hidden from the outside world and only allowing access to that data through specific methods. This helps to protect the data from unauthorized changes and keeps things clean and easy to manage.

In this article, we’ll take a closer look at how encapsulation works in programming languages like C++, Java, Python, and PHP.

What is Encapsulation?

Encapsulation in Object-Oriented Programming (OOP) is the idea of combining an object’s data (its state) and the methods (its behavior) that operate on that data into one single unit. In simple terms, encapsulation is like packaging everything an object needs to work into one container, which is a class. A class defines both the data (variables) and actions (methods or functions) that an object can perform. This helps keep everything organized and related in one place.

Encapsulation also means controlling access to the data inside an object. For example, you might not want other parts of the program to directly change the values inside the object, so you hide the data and only allow access through special methods. This prevents unwanted or accidental changes and keeps the object’s internal workings safe.

Real-time Examples of Encapsulation

Real-time Examples of Encapsulation

Here are three simple real-world examples to help you understand encapsulation better:

Example 1:

In a big company, there are different departments like sales, accounts, and production, each handling its own tasks. Let’s say someone from the accounts department needs to access sales data for a specific month. They can’t directly access the sales data. Instead, they must contact someone from the sales department to get the information they need. This is similar to encapsulation: the sales data is contained within the “Sales Department,” and only authorized people from that department can access it. Others must go through the proper channels to get the data, ensuring control and security.

Example 2:

When you log in to your email, a lot of processes happen in the background, and you have no control over them. For instance, the password you enter is encrypted and checked to make sure it’s correct, but you don’t see how it’s done. All you know is that once it’s verified, you get access to your account. This is another example of encapsulation: you don’t need to know how the system verifies your password, and you only interact with the result (access to your account), keeping certain processes hidden for security and simplicity.

Example 3:

Think of a television remote control. You press a button to change the channel or adjust the volume, but you don’t need to know how the remote sends signals to the TV or how the TV processes those signals. The internal workings of the remote and TV are hidden from you, and you only interact with the simple buttons on the remote. This is an example of encapsulation because the complex processes are hidden, and you only access what’s necessary to perform the task.

Encapsulation in Java

Encapsulation is a key concept in object-oriented programming (OOP) that involves bundling both the data and methods that operate on that data into a single unit, which is a class in Java. It allows you to hide the internal details of a class from outside access and only expose a public interface for interacting with the class.

In Java, encapsulation is achieved by making the instance variables of a class private. This means that these variables cannot be accessed directly from outside the class. To allow external access, getter and setter methods are used. These methods allow you to retrieve and modify the values of the private variables, while also giving you a chance to add any checks or rules to ensure the data is valid and consistent.

Example of Encapsulation in Java:

// Java Program to demonstrate Java Encapsulation

// Person Class

class Person {

    // Private instance variables (encapsulated)

    private String name;

    private int age;

    // Getter method for name

    public String getName() {

        return name;

    }

    // Setter method for name

    public void setName(String name) {

        this.name = name;

    }

    // Getter method for age

    public int getAge() {

        return age;

    }

    // Setter method for age

    public void setAge(int age) {

        this.age = age;

    }

}

// Driver Class

public class Main {

    public static void main(String[] args) {

        // Create a Person object

        Person person = new Person();

        // Set values using setter methods

        person.setName("John");

        person.setAge(30);

        // Get values using getter methods and display them

        System.out.println("Name: " + person.getName());

        System.out.println("Age: " + person.getAge());

    }

}

Output:

Name: John

Age: 30

Encapsulation in C++

Encapsulation in C++ is a fundamental concept in object-oriented programming (OOP) that combines both data and functions that work on that data into a single unit, known as a class. It’s like putting everything related to a particular object inside a box and only allowing access to the box through specific methods.

In C++, encapsulation is achieved by declaring class variables as private, which means no one can access them directly from outside the class. To interact with these variables, we use public methods called getters and setters. Getters allow us to fetch the value of a private variable, while setters let us modify it, with the option to add validation checks to ensure the data remains correct.

Example of Encapsulation in C++:

#include <iostream>

using namespace std;

class Student {

private:

    string name;  // private variable

    int age;      // private variable

public:

    // Setter for name

    void setName(string studentName) {

        name = studentName;

    }

    // Getter for name

    string getName() {

        return name;

    }

    // Setter for age

    void setAge(int studentAge) {

        if (studentAge > 0) {  // validate age

            age = studentAge;

        } else {

            cout << "Age must be positive!" << endl;

        }

    }

    // Getter for age

    int getAge() {

        return age;

    }

};

int main() {

    Student student;

    student.setName("John");

    student.setAge(20);


    cout << "Student Name: " << student.getName() << endl;

    cout << "Student Age: " << student.getAge() << endl;


    return 0;

}

Output:

Student Name: John

Student Age: 20

Encapsulation in Python

In Python, encapsulation is a concept where you bundle the data (attributes) and the methods (functions) that work on that data into a single unit, usually a class. The main idea behind encapsulation is to hide the internal details of the class and prevent external code from directly accessing or modifying the data. This helps maintain the integrity of the data and ensures it’s used properly. In Python, you can achieve encapsulation by making the attributes of a class private, which means they cannot be accessed directly from outside the class. Instead, you provide public methods, known as getter and setter methods, to allow controlled access to these private attributes. This way, you can add validation or rules in the getter or setter to ensure the data remains consistent.

Example of Encapsulation in Python

class Car:

    def __init__(self, make, model):

        self.__make = make  # Private attribute

        self.__model = model  # Private attribute

    # Getter method for 'make'

    def get_make(self):

        return self.__make

    # Setter method for 'make'

    def set_make(self, make):

        if make:  # You can add validation here

            self.__make = make

        else:

            print("Invalid make!")

    # Getter method for 'model'

    def get_model(self):

        return self.__model

    # Setter method for 'model'

    def set_model(self, model):

        if model:  # You can add validation here

            self.__model = model

        else:

            print("Invalid model!")

# Create an object of Car

car = Car("Toyota", "Corolla")


# Access data via getter methods

print(car.get_make())  # Output: Toyota

print(car.get_model())  # Output: Corolla


# Modify data via setter methods

car.set_make("Honda")

car.set_model("Civic")


# Check updated data

print(car.get_make())  # Output: Honda

print(car.get_model())  # Output: Civic




Output:

Toyota

Corolla

Honda

Civic

In this example, the attributes __make and __model are private, meaning they can’t be accessed directly from outside the class. The get_make and get_model methods are used to access their values, while the set_make and set_model methods allow you to modify them, with the added benefit of validating the input. This way, you have full control over how the data is accessed and changed.

Encapsulation in PHP

Encapsulation in PHP is a fundamental concept of object-oriented programming (OOP) that helps protect an object’s internal details from being accessed or modified directly from outside the class. Essentially, it means bundling the data (properties) and the methods (functions) that operate on that data into a single unit, which is the class. This ensures that the internal workings of an object are hidden from the outside world, and only a controlled interface is exposed for interacting with the object.

To achieve encapsulation in PHP, we make the properties of a class private, meaning they cannot be accessed directly from outside the class. Instead, we provide public methods, known as getters and setters, to allow controlled access to these private properties. The getter method is used to retrieve the value of a property, and the setter method is used to modify the value, often with added checks or validations.

Example of encapsulation in PHP

<?php

class Car {

    // Private property

    private $model;


    // Getter method to access the private property

    public function getModel() {

        return $this->model;

    }


    // Setter method to modify the private property

    public function setModel($model) {

        // Validation check before setting the value

        if($model != "") {

            $this->model = $model;

        } else {

            echo "Model name cannot be empty.";

        }

    }

}


// Create an object of the Car class

$myCar = new Car();


// Using setter method to set the model

$myCar->setModel("Toyota");


// Using getter method to access the model

echo "The car model is: " . $myCar->getModel();

?>

Output:

The car model is: Toyota

In this example:

  • The $model property is private, so it cannot be accessed directly from outside the Car class.
  • The setModel() method is used to set the value of the $model property, with validation to ensure the model name isn’t empty.

The getModel() method is used to get the value of the $model property

Types of Encapsulations in OOPS

Types of Encapsulations in OOPS

Encapsulation in Object-Oriented Programming (OOP) can be implemented in three main ways:

  • Data Member Encapsulation:
    In this technique, the data members (variables) of a class are kept private, meaning they can’t be accessed directly from outside the class. Instead, we use methods like setters and getters to change or retrieve their values. This ensures better control and security for the data.
  • Method Encapsulation:
    Some methods in a class are meant to handle internal tasks and don’t need to be accessed by users. These methods can be made private, so they’re hidden and only used within the class itself. This helps in simplifying the interface for users.
  • Class Encapsulation:
    Sometimes, a class might include another class that works behind the scenes to handle specific tasks or store certain data. If this inner class isn’t meant to be accessed by users, it can be made private. This keeps the implementation clean and prevents unnecessary access to internal details.

How to Hide Information Using Encapsulation

In object-oriented programming, encapsulation helps hide sensitive information by controlling who can access different parts of a class. This is done using access modifiers, which decide the visibility and accessibility of class structures like methods, variables, or data members. Access modifiers let programmers separate the public parts of a class (that everyone can use) from the private parts (hidden from users).

Here are the four types of access modifiers used in OOP:

  • Public
    Public members (like methods or variables) can be accessed from anywhere in the program. There are no restrictions—they can be used by objects of other classes without any problem.
  • Private
    Private members are only accessible within the same class. This means they can’t be accessed directly by other classes or objects. If you want to use them outside, you need to create public methods like setters or getters.
  • Protected
    Protected members are similar to private ones, but they also allow access to subclasses (child classes) that inherit from the parent class. This access depends on the inheritance type but is still more restrictive than public access.
  • Default
    If no access modifier is specified, the member is given default access. This means it can only be accessed within the same package (group of classes). Classes outside this package won’t have access to these members.

Advantages and Disadvantages of Encapsulation

Advantages & Disadvantages of Encapsulation

Advantages of Encapsulation

  • Better Code Reusability:
    Encapsulation lets you create a class once and use it to make multiple objects. By providing clear, public methods as the interface, it’s easier for others to understand what the class does and reuse it in different projects.
  • Increased System Stability:
    Encapsulation reduces the complexity of the system by minimizing the interdependence between different parts. This makes the program more stable and less likely to break when changes are made.
  • Easier Code Maintenance:
    Since encapsulation allows you to change the internal code of a class without affecting other parts of the program, it’s easier to update and maintain the code over time.
  • Better Data Security:
    By keeping sensitive data private, encapsulation ensures that data is accessed or modified only in controlled ways through public methods. This protects the internal state of objects and prevents unauthorized access.
  • Improved Code Clarity:
    Encapsulation keeps related variables and methods in one class, making the code more organized and easier to understand. This clarity also makes debugging and testing simpler.

Disadvantages of Encapsulation

  • Increased Code Complexity:
    Encapsulation requires additional code like setters, getters, and access modifiers, which can make the program more verbose and complex.
  • Performance Overhead:
    Accessing data through methods instead of directly can lead to slight performance overhead, especially in performance-critical systems.
  • Over-Engineering Risks:
    Encapsulation can sometimes lead to unnecessary complexity when applied too strictly, making simple tasks harder than they need to be.
  • Learning Curve:
    Beginners might find it harder to understand and implement encapsulation correctly, especially when balancing private and public access.

Conclusion

Encapsulation is a key concept in object-oriented programming (OOP). It refers to bundling data (variables) and the methods that operate on that data into a single unit, like a class, while restricting direct access to the internal details from outside the class.

In programming languages like Java, C++, Python, and PHP, every class is an example of encapsulation because it keeps methods and variables together. By declaring variables as private and providing public methods (like get() and set()), we control how other parts of the program can interact with the class’s data.

What is Encapsulation in OOPS Explained with Examples

The Ultimate Guide to Segmentation in Operating

Leave a comment

Your email address will not be published. Required fields are marked *