👁 Preview — Study, Practice and Revise are open; mock tests and the rest of the syllabus unlock on subscription. Unlock all · ₹4,999
← Back to OOP Concepts
Study mode

Encapsulation

Introduction to Encapsulation

In Object-Oriented Programming (OOP), encapsulation is a fundamental concept that combines data (variables) and the methods (functions) that operate on that data into a single unit called a class. More importantly, encapsulation restricts direct access to some of an object's components, which helps protect the integrity of the data inside the object.

Think of encapsulation as a protective shield around the data inside an object. Just like a capsule protects medicine inside it, encapsulation protects the internal state of an object from unintended or harmful changes. This ensures that the object controls how its data is accessed or modified.

Encapsulation promotes modularity and maintainability in software by clearly defining boundaries between different parts of a program. It allows programmers to change the internal workings of a class without affecting other parts of the program that use the class.

Encapsulation Basics

At its core, encapsulation involves two key ideas:

  • Data Hiding: Keeping the internal data of a class hidden from outside access.
  • Data Bundling: Grouping related data and methods together inside a class.

To achieve data hiding, programming languages provide access modifiers that control the visibility of class members (variables and methods). The most common access modifiers are:

  • private: Members are accessible only within the class itself.
  • public: Members are accessible from anywhere.
  • protected: Members are accessible within the class and its subclasses (more on this later).

Because private data cannot be accessed directly from outside the class, classes provide getter and setter methods. These are public methods that allow controlled access to private variables. Getters retrieve the value, and setters modify the value, often including validation to prevent invalid data.

graph TD    Class[Class: BankAccount]    PrivateVar[Private Variable: balance]    PublicGet[Public Method: getBalance()]    PublicSet[Public Method: deposit(amount), withdraw(amount)]    User[User Code]    Class --> PrivateVar    Class --> PublicGet    Class --> PublicSet    User -->|Cannot access directly| PrivateVar    User -->|Calls| PublicGet    User -->|Calls| PublicSet

Access Modifiers in Detail

Understanding access modifiers is crucial for implementing encapsulation correctly. Here's a detailed look at each:

Access Modifier Accessible From Typical Use
private Only within the defining class Hide sensitive data and internal details
public Anywhere in the program Methods and variables meant for external use
protected Within the class and its subclasses Allow controlled access in inheritance hierarchies

For example, a bank account's balance should be private to prevent unauthorized changes. However, methods to deposit or withdraw money are public so users can interact with the account safely.

Encapsulation vs Abstraction

While encapsulation and abstraction are related OOP concepts, they serve different purposes and are often confused. Let's clarify:

Aspect Encapsulation Abstraction
Definition Wrapping data and methods into a single unit and hiding data from outside access Hiding complex implementation details and showing only essential features
Focus Data hiding and access control Reducing complexity by exposing only necessary information
Example Private variables with public getter/setter methods Using an interface or abstract class to define methods without showing implementation
Purpose Protect object integrity and prevent unauthorized data access Simplify usage by hiding internal workings

In short, encapsulation is about how data is protected inside a class, while abstraction is about what is shown to the user of the class.

Worked Examples

Example 1: Bank Account Class Encapsulation Easy
Create a BankAccount class that encapsulates the account balance. The balance should be private, and the class should provide public methods to deposit and withdraw money safely.

Step 1: Define the class with a private variable balance initialized to zero.

Step 2: Create a public method deposit(amount) that adds money to the balance. It should check that the amount is positive.

Step 3: Create a public method withdraw(amount) that subtracts money from the balance if sufficient funds exist.

Step 4: Provide a public method getBalance() to return the current balance.

Answer:

class BankAccount {  private double balance = 0.0;  public void deposit(double amount) {    if (amount > 0) {      balance += amount;    } else {      System.out.println("Invalid deposit amount");    }  }  public void withdraw(double amount) {    if (amount > 0 && amount <= balance) {      balance -= amount;    } else {      System.out.println("Invalid or insufficient funds");    }  }  public double getBalance() {    return balance;  }}    
Example 2: Employee Salary Management Medium
Design an Employee class that encapsulates the salary. The salary should be private. Implement getter and setter methods where the setter validates that the salary cannot be negative.

Step 1: Declare a private variable salary.

Step 2: Create a public getter getSalary() to return the salary.

Step 3: Create a public setter setSalary(double amount) that sets the salary only if the amount is non-negative.

Answer:

class Employee {  private double salary;  public double getSalary() {    return salary;  }  public void setSalary(double amount) {    if (amount >= 0) {      salary = amount;    } else {      System.out.println("Salary cannot be negative");    }  }}    
Example 3: Product Inventory Update Medium
Create a Product class with a private variable stockQuantity. Implement methods to add stock and sell products, ensuring stock quantity never becomes negative.

Step 1: Declare a private variable stockQuantity initialized to zero.

Step 2: Implement a public method addStock(int amount) that increases stock if amount is positive.

Step 3: Implement a public method sellProduct(int amount) that decreases stock only if enough stock is available.

Answer:

class Product {  private int stockQuantity = 0;  public void addStock(int amount) {    if (amount > 0) {      stockQuantity += amount;    } else {      System.out.println("Invalid stock amount");    }  }  public void sellProduct(int amount) {    if (amount > 0 && amount <= stockQuantity) {      stockQuantity -= amount;    } else {      System.out.println("Insufficient stock or invalid amount");    }  }  public int getStockQuantity() {    return stockQuantity;  }}    
Example 4: Incorrect Access Correction Easy
A student tries to access a private variable balance of a BankAccount object directly and gets an error. Show how to fix this using encapsulation.

Step 1: Identify that balance is private and cannot be accessed directly.

Step 2: Use the public getter method getBalance() to access the balance.

Step 3: Use public methods like deposit() and withdraw() to modify the balance instead of direct access.

Answer:

// Incorrect:BankAccount account = new BankAccount();double bal = account.balance;  // Error: balance is private// Correct:double bal = account.getBalance();account.deposit(1000);account.withdraw(500);    
Example 5: Encapsulation in Inheritance Context Hard
Create a base class Person with a protected variable name. Derive a subclass Student that accesses name and adds a method to display the student's name.

Step 1: Define name as protected in Person so subclasses can access it but outside classes cannot.

Step 2: In Student, create a method display() that prints the name.

Answer:

class Person {  protected String name;  public Person(String name) {    this.name = name;  }}class Student extends Person {  public Student(String name) {    super(name);  }  public void display() {    System.out.println("Student Name: " + name);  }}    

Explanation: The protected access modifier allows Student to access name directly, but code outside these classes cannot access name directly, preserving encapsulation.

Tips & Tricks

Tip: Always use private variables and public getter/setter methods

When to use: When designing classes to protect data integrity and control access

Tip: Validate data inside setter methods

When to use: To prevent invalid data assignment and maintain object consistency

Tip: Remember: Encapsulation is about hiding data, not hiding methods

When to use: To avoid confusion between encapsulation and abstraction

Tip: Use protected access modifier when subclasses need access but data should remain hidden from other classes

When to use: When designing class hierarchies with inheritance

Tip: Think of encapsulation as a protective shield around the data

When to use: To easily recall the concept during exams and coding

Common Mistakes to Avoid

❌ Accessing private variables directly from outside the class
✓ Use public getter and setter methods to access or modify private variables
Why: Students often forget access modifiers and try to access data directly, breaking encapsulation
❌ Not validating data in setter methods
✓ Include validation logic inside setters to ensure data integrity
Why: Students assume setters are just simple assignments, leading to invalid object states
❌ Confusing encapsulation with abstraction
✓ Remember encapsulation is about data hiding; abstraction is about hiding complexity
Why: Both are related OOP concepts but serve different purposes, causing confusion
❌ Using public variables instead of private with getters/setters
✓ Always declare variables private and provide controlled access methods
Why: Public variables expose internal data and violate encapsulation principles
❌ Overusing protected access modifier
✓ Use protected only when subclass access is necessary; otherwise prefer private
Why: Excessive use of protected can lead to poor encapsulation and harder maintenance
Key Concept

Encapsulation

Encapsulation bundles data and methods into a single unit and restricts direct access to protect object integrity. It uses access modifiers like private and public to control visibility, promoting security, modularity, and maintainability.

Curated videos per subtopic
Top YouTube explainers, AI-ranked for your exam and language. Unlocks with subscription.
Unlock

Try Practice next.

Progress tracking is paywalled — subscribe to mark subtopics as understood and save your streak.

Go to practice →
Ask a doubt
Encapsulation · 10 free messages
Ask me anything about this subtopic. You have 10 free messages this session — chat history isn't saved in preview.