What is Encapsulation in OOPS? (Explained in Detail with Examples)

By | January 4, 2024

Varun Saharawat is a seasoned professional in the fields of SEO and content writing. With a profound knowledge of the intricate aspects of these disciplines, Varun has established himself as a valuable asset in the world of digital marketing and online content creation.


encapsulation in oops

Encapsulation in OOPS refers to the bundling of data and methods that operate on this data into a single unit, commonly known as a class. Keep reading to find examples and more details!

Encapsulation in OOPS: No one concept in object-oriented programming is more fundamental yet equally misunderstood than encapsulation. While its core principle seems simple—wrap up related data and code together so that they can be accessed only through an interface—encapsulation is often overlooked or mistakenly conflated with another OOP pillar of abstraction. Yet encapsulation lies at the heart of truly object-oriented design.

So, whether you’re a beginner or an experienced programmer looking to improve your skills, understanding encapsulation is crucial for writing efficient and maintainable code. With practice and patience, you will become comfortable with implementing it in your own projects. 

And if you want to take your Java skills to the next level, we highly recommend checking out Decode Java+DSA 1.0 by Physics Wallah course. Plus, as a reader of this blog post, you can use the “READER” coupon at checkout to receive exclusive discounts on the course! So don’t wait any longer; start mastering encapsulation and elevate your coding game today!

What is Encapsulation in OOPS with Example?

Encapsulation is a vital concept in Object-Oriented Programming that allows us to hide the internal complexities of our code and only expose what’s necessary for other parts of our program to interact with. It promotes better code organization, makes debugging easier, and increases security by preventing unwanted access to private variables and methods. 

Through various examples, encapsulation can be achieved through a combination of access modifiers, getter and setter methods, and proper design patterns like data hiding and abstraction. 

Example:

# Define a class ‘Employee’ to demonstrate encapsulation in Python

class Employee:

    # Constructor to initialize private attributes

    def __init__(self, name, salary):

        self.__name = name  # Private attribute

        self.__salary = salary  # Private attribute

    # Public method to display employee details

    def display_details(self):

        print(f”Employee Name: {self.__name}”)

        print(f”Employee Salary: {self.__salary}”)

    # Public method to encapsulate and set employee salary

    def set_salary(self, salary):

        if salary > 0:  # Validate the input

            self.__salary = salary

        else:

            print(“Invalid salary value.”)

    # Public method to encapsulate and get employee salary

    def get_salary(self):

        return self.__salary

# Create an object of the ‘Employee’ class

employee = Employee(“John Doe”, 50000)

# Accessing public methods to set and display employee details

employee.display_details()

# Accessing public methods to set and get employee salary (encapsulation)

employee.set_salary(55000)  # Valid salary update

print(f”Updated Employee Salary: {employee.get_salary()}”)

Encapsulation in OOPS C++ With Example

Encapsulation in C++ is a core principle in Object-Oriented Programming (OOP) that combines data (attributes) and methods (functions) into a single unit known as a class, and restricts access to some of its components. In C++, encapsulation is achieved using access specifiers such as public, private, and protected.

#include <iostream>

#include <string>

// Define a class ‘Employee’ to demonstrate encapsulation

class Employee {

private:  // Private access specifier

    std::string name;

    double salary;

public:  // Public access specifier

    // Constructor to initialize the attributes

    Employee(std::string n, double s) {

        name = n;

        salary = s;

    }

    // Public method to display employee details

    void displayDetails() {

        std::cout << “Employee Name: ” << name << std::endl;

        std::cout << “Employee Salary: ” << salary << std::endl;

    }

    // Public methods to encapsulate and access the private attributes

    void setSalary(double s) {

        if (s > 0) {  // Validate the input

            salary = s;

        } else {

            std::cout << “Invalid salary value.” << std::endl;

        }

    }

    double getSalary() {

        return salary;

    }

private:  // Private access specifier

    // Private method (accessible only within the class)

    double calculateBonus() {

        return salary * 0.1;  // 10% bonus calculation

    }

};

// Main function to test encapsulation

int main() {

    // Create an object of the ‘Employee’ class

    Employee employee(“John Doe”, 50000);

    // Accessing public methods to set and display employee details

    employee.displayDetails();

    // Accessing public methods to set and get employee salary (encapsulation)

    employee.setSalary(55000);  // Valid salary update

    std::cout << “Updated Employee Salary: ” << employee.getSalary() << std::endl;

    // Attempting to access private attributes and methods (not accessible outside the class)

    // std::cout << employee.salary;  // Uncomment to see the error

    // std::cout << employee.calculateBonus();  // Uncomment to see the error

    return 0;

}

Explanation:

  1. Private Attributes (private: std::string name; and private: double salary;): The name and salary attributes are declared as private within the Employee class, ensuring that they are only accessible within the class and encapsulating their direct access from outside.
  2. Public Methods (public:): The displayDetails, setSalary, and getSalary methods are declared as public, encapsulating the operations related to displaying employee details and manipulating the salary attribute through controlled access.
  3. Private Method (private:): The calculateBonus method is declared as private within the Employee class, encapsulating the bonus calculation logic and restricting its access to only within the class.

Encapsulation in OOPS Java With Example

Encapsulation is a fundamental principle in Object-Oriented Programming (OOP) that involves bundling the data (attributes) and methods (functions) into a single unit known as a class and restricting access to some of the object’s components. In Java, encapsulation is achieved using access modifiers such as public, private, and protected.

// Define a class ‘Employee’ to demonstrate encapsulation

public class Employee {

    // Private attributes (accessible only within the class)

    private String name;

    private double salary;

    // Public constructor to initialize the attributes

    public Employee(String name, double salary) {

        this.name = name;

        this.salary = salary;

    }

    // Public method to display employee details

    public void displayDetails() {

        System.out.println(“Employee Name: ” + name);

        System.out.println(“Employee Salary: ” + salary);

    }

    // Public method to set salary (encapsulating the attribute)

    public void setSalary(double salary) {

        if (salary > 0) {  // Validate the input

            this.salary = salary;

        } else {

            System.out.println(“Invalid salary value.”);

        }

    }

    // Public method to get salary (encapsulating the attribute)

    public double getSalary() {

        return salary;

    }

    // Private method (accessible only within the class)

    private double calculateBonus() {

        return salary * 0.1;  // 10% bonus calculation

    }

}

// Main class to test encapsulation

public class TestEncapsulation {

    public static void main(String[] args) {

        // Create an object of the ‘Employee’ class

        Employee employee = new Employee(“John Doe”, 50000);

        // Accessing public methods to set and display employee details

        employee.displayDetails

();

// Accessing public methods to set and get employee salary (encapsulation)

    employee.setSalary(55000);  // Valid salary update

    System.out.println(“Updated Employee Salary: ” + employee.getSalary());

    // Attempting to access private attributes and methods (not accessible outside the class)

    // System.out.println(employee.salary);  // Uncomment to see the error

    // System.out.println(employee.calculateBonus());  // Uncomment to see the error

}

}

Encapsulation in OOPS Python With Example

Encapsulation is one of the fundamental concepts in Object-Oriented Programming (OOP) that allows bundling of data (attributes) and methods (functions) into a single unit known as a class and restricts direct access to some of the object’s components. In Python, encapsulation is achieved using access specifiers such as public, protected, and private.

# Define a class ‘Employee’ to demonstrate encapsulation

class Employee:

    # Public attribute (accessible from outside the class)

    def __init__(self, name, salary):

        self.name = name  # Public attribute

        self.__salary = salary  # Private attribute

    # Public method to display employee details

    def display_details(self):

        print(f”Employee Name: {self.name}”)

        print(f”Employee Salary: {self.__salary}”)  # Accessing private attribute within class

    # Private method (accessible only within the class)

    def __calculate_bonus(self):

        return self.__salary * 0.1  # 10% bonus calculation (private method)

# Create an object of the ‘Employee’ class

employee = Employee(“John Doe”, 50000)

# Accessing public attributes and methods (encapsulation allows access)

employee.display_details()

# Attempting to access private attribute directly (raises AttributeError)

# print(employee.__salary)  # Uncomment to see the error

# Attempting to access private method directly (raises AttributeError)

# print(employee.__calculate_bonus())  # Uncomment to see the error

# Accessing private attribute indirectly (through name mangling)

print(f”Employee Salary (Indirect Access): {employee._Employee__salary}”)  # Name mangling

Explanation:

  1. Public Attribute (self.name): The name attribute is a public attribute accessible from outside the class, allowing users to view or modify it directly.
  2. Private Attribute (self.__salary): The __salary attribute is a private attribute indicated by prefixing with double underscores (__), making it inaccessible from outside the class. Python uses name mangling to access private attributes indirectly within the class.
  3. Public Method (display_details): The display_details method is a public method that displays the employee’s name and salary, encapsulating the logic within the class and allowing users to invoke it.
  4. Private Method (__calculate_bonus): The __calculate_bonus method is a private method indicated by prefixing with double underscores (__), making it accessible only within the class, encapsulating the bonus calculation logic.

Also Read: Top 10 Toughest Courses in India of 2024

Abstraction in OOPS

Abstraction is a crucial principle in Object-Oriented Programming (OOP) that focuses on hiding complex implementation details and exposing only essential features or functionalities of an object to interact with other objects or systems. Abstraction facilitates the creation of high-level representations of real-world entities, enabling developers to model and design systems using simplified and intuitive interfaces.

  • Abstraction allows developers to hide intricate details of an object’s internal structure, behavior, or operations, providing a simplified and consistent interface for interacting with objects.
  • By encapsulating complex logic and operations within classes, abstraction promotes modularity, reduces complexity, and enhances code readability and maintainability.
  • Abstraction involves defining abstract classes or interfaces that declare the contract or blueprint for derived classes.
  • Abstract classes define abstract methods (without implementation), providing a template or structure for derived classes to implement specific functionalities, ensuring consistency and adherence to defined specifications.
  • Abstraction facilitates generalization by identifying common attributes, behaviors, or functionalities shared among related objects, promoting code reusability, and minimizing redundancy.
  • Through inheritance and polymorphism, abstraction supports specialization by allowing derived classes to extend or override inherited functionalities, adapting to specific requirements or variations while maintaining a consistent interface.
  • Abstraction simplifies system design by representing complex real-world entities or systems using abstracted models, concepts, or components.
  • By focusing on essential features and functionalities, abstraction enables developers to manage complexity, enhance understanding, and facilitate communication among stakeholders, ensuring alignment with business requirements and objectives.
  • Abstraction enhances system flexibility by decoupling dependencies, isolating changes, and promoting modular design principles.
  • By abstracting common functionalities and variations, developers can extend, modify, or adapt systems more efficiently, supporting evolving requirements, technologies, and business environments.

Real-Life Encapsulation Examples

Here’s a the real-life encapsulation examples:

1) Medical Prescription System

Imagine visiting a doctor’s clinic. The doctor assesses your condition, diagnosis, and prescribes specific medication. However, you do not have direct access to the doctor’s prescription pad or their computer system to modify or add medications yourself. 

Instead, the doctor provides you with a sealed prescription detailing the required medications, dosage, and instructions. In this scenario, the prescription acts as an encapsulated entity. The doctor retains exclusive control and access to modify or add prescriptions, ensuring accuracy, consistency, and safety for patients.

2) Secure Banking Systems

Consider the process of conducting online banking transactions. When you initiate a fund transfer or access your account details, multiple secure layers and processes operate behind the scenes. However, as a user, you do not have direct access to modify transaction protocols, alter security algorithms, or manipulate account balances. 

The banking system encapsulates these critical operations, ensuring that users interact only through designated interfaces like mobile apps or web portals. This encapsulation safeguards sensitive financial data, prevents unauthorized access, and maintains the integrity and security of the banking system.

3) Smart Home Automation Systems

In modern homes equipped with smart automation systems, various interconnected devices such as thermostats, security cameras, lights, and appliances communicate and operate seamlessly. However, users do not directly manipulate the underlying code, algorithms, or communication protocols governing these devices’ interactions.

Instead, homeowners access a user-friendly interface or application that encapsulates complex operations, allowing them to control and monitor devices effortlessly. This encapsulation simplifies user interaction, enhances user experience, and ensures the seamless integration and operation of diverse smart home components.

4) Restaurant Ordering System

When dining at a restaurant, patrons interact with a waiter or use a digital menu system to place their orders. However, customers do not have direct access to the kitchen, inventory management systems, or billing processes. 

Behind the scenes, the restaurant encapsulates these operations, ensuring efficient order processing, inventory management, and billing accuracy. This encapsulation facilitates smooth restaurant operations, optimizes resource utilization, and enhances customer satisfaction by delivering timely and accurate services.

Also Read: 7 Best Coding Challenge Websites in 2024

Features of Encapsulation in OOPS

Encapsulation is a fundamental concept in Object-Oriented Programming (OOP) that combines data (attributes) and methods (functions) into a single unit known as a class. This concept promotes the bundling of data (attributes) and methods that operate on that data within a single entity, ensuring that the internal state of an object is protected and accessed only through defined interfaces. Here are some key features of encapsulation in OOP:

1) Data Hiding:

  • Encapsulation facilitates data hiding by restricting direct access to an object’s internal state (attributes) from outside the class.
  • Private access specifiers ensure that sensitive data remains concealed, preventing unauthorized modifications or access.

2) Access Control:

  • Encapsulation allows developers to define access levels (public, private, protected) for class members, determining their visibility and accessibility.
  • Access specifiers ensure controlled interactions with class attributes and methods, enhancing security and modularity.

3) Modularity and Abstraction:

  • Encapsulation promotes modularity by encapsulating the implementation details within a class, separating the external interface from internal implementation.
  • By encapsulating complex logic and operations, developers can abstract intricate functionalities, providing a simplified and consistent interface for interacting with objects.

4) Data Integrity:

  • Encapsulation ensures data integrity by encapsulating data within defined boundaries and providing controlled access through methods (getters and setters).
  • By encapsulating data manipulation within methods, developers can enforce validation rules, maintain consistency, and prevent invalid state transitions.

5) Enhanced Security:

  • Encapsulation enhances security by encapsulating sensitive data and operations within a class, preventing unauthorized access and modifications.
  • Private access specifiers ensure that critical data and methods are inaccessible from external entities, safeguarding the integrity and confidentiality of object state.

6) Code Reusability and Maintainability:

  • Encapsulation facilitates code reusability by encapsulating common functionalities within classes, promoting code modularization, and reducing redundancy.
  • By encapsulating implementation details, developers can modify the internal structure, methods, or attributes of a class without affecting external code or dependent components, enhancing maintainability.

Role of Access Specifiers in Encapsulation in OOPS

In Object-Oriented Programming (OOP), encapsulation is a fundamental concept that combines data (attributes) and methods (functions) into a single unit known as a class. The main idea behind encapsulation is to restrict direct access to some of an object’s components, which then helps in preventing unintended interference and misuse of data.

Access specifiers play a crucial role in implementing encapsulation by defining the level of accessibility for class members. In many OOP languages like Java, C++, and C#, there are typically three primary access specifiers:

1) Public:

  • Members declared as public are accessible from any other class or method.
  • They allow unrestricted access and can be accessed from outside the class in which they are declared.
  • This specifier is often used for class methods or attributes that need to be accessed globally.

2) Private:

  • Members declared as private are accessible only within the class in which they are declared.
  • They cannot be accessed or modified from outside the class, ensuring that the internal implementation details are hidden from external interference.
  • This specifier is commonly used to encapsulate sensitive or critical data, providing a secure boundary for class attributes.

3) Protected:

  • Members declared as protected are accessible within the class in which they are declared and its subclasses.
  • They provide a level of encapsulation by allowing restricted access to derived classes while preventing access from unrelated classes.
  • This specifier is useful for establishing a hierarchical relationship between classes, where derived classes need access to specific attributes or methods of their base class.

Also Read: Python vs Java: Which is Best for Machine learning algorithm

Benefits of Using Access Specifiers in Encapsulation:

  • Data Hiding: Access specifiers facilitate data hiding by restricting direct access to class members, ensuring that sensitive data remains encapsulated within the class.
  • Modularity: By encapsulating data and methods, access specifiers promote modularity by separating the class’s interface (public methods) from its implementation (private methods and attributes).
  • Enhanced Security: Private access specifiers protect critical data from unauthorized access and modification, enhancing the security and integrity of the object’s state.
  • Flexibility and Maintainability: Encapsulation using access specifiers improves code flexibility and maintainability by encapsulating the class’s internal details, allowing developers to modify the internal implementation without affecting the external interface.

If you are looking to improve your skills in Java or any other programming language, I highly recommend checking out Physics Wallah’s “Decode Java+DSA 1.0″ course. This comprehensive course not only covers the basics of Java but also dives deep into data structures and algorithms, all taught by one of India’s top educators team!

Encapsulation in OOPS FAQs

What is an encapsulation in OOPs?

Encapsulation in OOPs is a concept where data (attributes) and methods (functions) are combined into a single unit called a class, and access to them is restricted to ensure data integrity and security.

What is abstraction and encapsulation in OOP?

Abstraction focuses on hiding complex implementation details and displaying only essential features of an object. Encapsulation involves bundling data and methods into a class and restricting access to ensure controlled interactions and data integrity.

What is encapsulation in OOP C++?

In C++, encapsulation refers to bundling data (attributes) and functions (methods) within a class, using access specifiers like private, public, and protected to control access to class members and ensure data integrity.

What is encapsulation called?

Encapsulation is often referred to as the bundling of data and methods into a single unit (class) and restricting access to the internal components, ensuring controlled interactions and maintaining the integrity of the data within the object.

Telegram Group Join Now
WhatsApp Channel Join Now
YouTube Channel Subscribe
Scroll to Top
close
counselling
Want to Enrol in PW Skills Courses
Connect with our experts to get a free counselling & get all your doubt cleared.