ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Object Oriented Programming
    CC-211
    Progress0 / 24 topics
    Topics
    1. Object-Oriented Design: History and Advantages2. Object-Oriented Programming: Terminology and Features3. Classes and Objects4. Data Encapsulation5. Constructors and Destructors6. Access Modifiers7. Const vs Non-Const Functions8. Static Data Members and Functions9. Function Overloading10. Operator Overloading11. Identification of Classes and Their Relationships12. Composition13. Aggregation14. Inheritance15. Multiple Inheritances16. Polymorphism17. Abstract Classes18. Interfaces19. Generic Programming Concepts20. Function Templates21. Class Templates22. Standard Template Library23. Object Streams: Data and Object Serialization24. Exception Handling
    CC-211›Data Encapsulation
    Object Oriented ProgrammingTopic 4 of 24

    Data Encapsulation

    6 minread
    1,099words
    Intermediatelevel

    Data Encapsulation in Object-Oriented Programming (OOP)

    Data Encapsulation is one of the fundamental concepts of Object-Oriented Programming (OOP). It refers to the bundling of data (attributes) and the methods (functions) that operate on that data into a single unit, known as a class. In addition, encapsulation involves restricting direct access to some of an object's components and only allowing controlled access via public methods, commonly known as getters and setters.

    The primary goal of encapsulation is to protect the internal state of an object from unwanted changes and to hide implementation details from the outside world. This helps to ensure that the object’s data is manipulated only in well-defined and controlled ways.


    Key Concepts of Data Encapsulation

    1. Private Data Members:

      • Data members (attributes) of a class are typically made private so that they cannot be accessed directly from outside the class. This helps protect the data from being modified in unintended ways.
    2. Public Getter and Setter Methods:

      • Public methods, called getters and setters, are used to access or modify the private data members.
        • Getter methods allow reading the values of private attributes.
        • Setter methods allow modifying the values of private attributes, typically with some validation or logic.
    3. Control Over Data:

      • By using encapsulation, the class designer can control how the data is accessed or modified. For instance, a setter method might validate data before modifying an attribute to ensure the object's state remains valid.
    4. Information Hiding:

      • Encapsulation hides the internal state of an object from the outside world. External code interacts with the object only through its public interface (methods), not through direct access to its internal state.

    Advantages of Data Encapsulation

    1. Data Integrity:

      • Encapsulation ensures that the internal state of an object cannot be changed in unpredictable or invalid ways. Only methods provided by the class can change the object's state, and these methods can enforce rules to ensure that data is always in a valid state.
    2. Modularity:

      • With encapsulation, the implementation of an object can be modified without affecting other parts of the program that use the object. As long as the public interface (methods) remains the same, you can change the internal workings of the class without impacting external code.
    3. Security:

      • By making data members private, you prevent unauthorized access to sensitive data, which adds an extra layer of security to your application.
    4. Reduced Complexity:

      • The external interface of an object is simplified, as users do not need to know about its internal implementation. They can interact with the object through its public methods.
    5. Code Reusability and Maintenance:

      • Encapsulation allows for better code maintenance and reuse, since the internal workings of the class are separated from its public interface. This makes it easier to fix bugs, update logic, or extend functionality without affecting other parts of the system.

    Example of Data Encapsulation in C++

    Let’s see an example of how data encapsulation works in C++:

    #include <iostream>
    using namespace std;
    
    class BankAccount {
    private:
        double balance;  // Private data member
    
    public:
        // Constructor to initialize balance
        BankAccount(double initial_balance) {
            if (initial_balance > 0) {
                balance = initial_balance;
            } else {
                balance = 0;  // If invalid balance is provided, set it to 0
            }
        }
    
        // Getter method to access the balance
        double getBalance() {
            return balance;
        }
    
        // Setter method to deposit money (ensures positive deposits)
        void deposit(double amount) {
            if (amount > 0) {
                balance += amount;
            } else {
                cout << "Deposit amount must be positive!" << endl;
            }
        }
    
        // Setter method to withdraw money (ensures no overdraft)
        void withdraw(double amount) {
            if (amount > 0 && amount <= balance) {
                balance -= amount;
            } else {
                cout << "Invalid withdrawal amount!" << endl;
            }
        }
    };
    
    int main() {
        BankAccount account(1000);  // Create a bank account object with an initial balance of 1000
    
        // Access and manipulate the balance via getter and setter methods
        cout << "Initial Balance: $" << account.getBalance() << endl;
    
        account.deposit(500);  // Deposit $500
        cout << "After Deposit: $" << account.getBalance() << endl;
    
        account.withdraw(200);  // Withdraw $200
        cout << "After Withdrawal: $" << account.getBalance() << endl;
    
        account.withdraw(2000);  // Try to withdraw an amount greater than the balance
        cout << "After Attempted Overdraft: $" << account.getBalance() << endl;
    
        return 0;
    }
    

    Explanation of the Code:

    • Private Data Member:

      • The balance is a private data member of the BankAccount class, so it cannot be accessed directly from outside the class.
    • Getter Method:

      • getBalance() is a public method that allows access to the value of the balance. This is the only way to retrieve the balance from outside the class.
    • Setter Methods:

      • deposit(double amount) and withdraw(double amount) are public methods that allow modification of the balance. However, these methods include logic to ensure that only valid operations are performed (e.g., no negative deposits and no overdrafts).
    • Encapsulation in Action:

      • External code interacts with the BankAccount object only through its public methods (getBalance(), deposit(), withdraw()). The internal state (balance) is protected from direct access, ensuring the integrity of the object's data.

    Real-World Example of Data Encapsulation

    A real-world analogy of encapsulation is like a TV remote control:

    • The TV remote provides a public interface (buttons like Power, Volume Up, Channel Change) to interact with the TV.
    • The internal workings of the TV (how the circuit is powered or how the channels are changed) are hidden from the user.
    • The user does not need to know how the TV works internally; they only need to know how to use the remote (the public interface).
    • The internal data of the TV (its settings, current volume, etc.) is protected from being directly changed by the user through the remote.

    Summary of Data Encapsulation

    • Encapsulation is the process of bundling data and methods that operate on that data within a single unit (a class).
    • It restricts direct access to some of an object's components and allows controlled access via getter and setter methods.
    • Encapsulation helps protect an object’s internal state, ensures data integrity, reduces complexity, and provides security and modularity.

    Encapsulation is a core principle of OOP, making it easier to manage complex systems by isolating object details and exposing only necessary interfaces. It enables safer and more maintainable code by controlling how data is accessed and modified.

    Previous topic 3
    Classes and Objects
    Next topic 5
    Constructors and Destructors

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time6 min
      Word count1,099
      Code examples0
      DifficultyIntermediate