πŸŽ‰ Special Offer !    Code: GET300OFF    Flat β‚Ή300 OFF on every Java Course
Grab Deal πŸš€

Encapsulation in Java  


Introduction
  • Encapsulation is the mechanism of binding data (variables) and actions (methods) into a single unit, called a class.
  • Technically, every class is an example of encapsulation.
  • Real World Example:
    Capsule

    A capsule in which main medicine is encapsulated.

    Car

    A car is in which engine, wheels, and other parts are encapsulated.

  • Java Program Example:
    class Car
    {
        // Data members (variables)
        String brand;
        int speed;
    
        // Method to display person details
        void setDetails(String b, int s)
        {
            brand = b;
            speed = s;
        }
        void printDetails()
        {
            System.out.println("Brand : " + brand);
            System.out.println("Speed : " + speed);
        }
    }
    
    public class Main
    {
        public static void main(String[] args)
        {
            // Creating object
            Car c = new Car();
    
            // Calling method
            c.setDetails("Tata", 100);
        }
    }
    Output:
    Brand : Tata
    Speed : 100
  • Explanation:
    • Person class contains both data (name, age) and method (displayInfo()).
    • Everything is inside one unit (class) β€” this is the essence of encapsulation.

Rules for Encapsulation :-
  • 1. Private Variables :
    • Declare variables as private so that they cannot be accessed directly from outside the class.
  • 2. Public Getter & Setter Methdos :
    • Provide public getter and setter methods to access and modify the private variables.
Actual/Proper Encapsulated Java Program Example :-
  • class Car
    {
        // Private data members (encapsulated)
        private String brand;
        private int speed;
    
        // Public setter for brand
        public void setBrand(String brand)
        {
            this.brand = brand;
        }
    
        // Public getter for brand
        public String getBrand()
        {
            return brand;
        }
    
        // Public setter for speed
        public void setSpeed(int speed)
        {
            // Optional: simple validation
            if (speed >= 0)
            {
                this.speed = speed;
            }
        }
    
        // Public getter for speed
        public int getSpeed()
        {
            return speed;
        }
    
        // Method to print car details
        public void printDetails()
        {
            System.out.println("Brand : " + brand);
            System.out.println("Speed : " + speed);
        }
    }
    
    public class MainApp
    {
        public static void main(String[] args)
        {
            Car c = new Car();
    
            // Setting values using setters
            c.setBrand("Tata");
            c.setSpeed(100);
    
            // Printing car details
            c.printDetails();
        }
    }
    
    Output:
    Speed : Tata
    Speed : 100

Use of Encapsulation :-
  1. Protects data: Hides data from direct access using private variables.
  2. Controls data access: Provides controlled access through public getters and setters.
  3. Allows data validation: Enables validation before updating variables (e.g., checking valid input).
  4. Improves code maintainability: Keeps internal implementation hidden, making changes easier.
  5. Enhances flexibility: Internal logic can change without affecting external code.
  6. Prevents unauthorized or accidental modifications: Limits who and how data can be changed.
Below is the program elaborating above uses :
  • Example:
    // Class demonstrating proper encapsulation
    class Account
    {
        // πŸ”’ Protects data by hiding it from direct access
        private String accountHolder;
        private double balance;
    
        // βœ… Public getter (controlled access to private data)
        public String getAccountHolder()
        {
            return accountHolder;
        }
    
        // βœ… Public setter (controlled access with flexibility for future validation)
        public void setAccountHolder(String accountHolder)
        {
            this.accountHolder = accountHolder;
        }
    
        // βœ… Getter for balance
        public double getBalance()
        {
            return balance;
        }
    
        // πŸ’° Method to deposit money
        public void deposit(double amount)
        {
            // πŸ›‘οΈ Allows data validation before modifying balance
            if (amount > 0)
            {
                balance = balance + amount;
                System.out.println("You have deposited " + amount + " Rs.");
                System.out.println("New balance is: " + getBalance() + " Rs.");
            }
            else
            {
                System.out.println("Invalid deposit amount");
            }
        }
    
        // πŸ’Έ Method to withdraw money
        public void withdraw(double amount)
        {
            // πŸ›‘οΈ Data validation: prevents negative balance
            if (amount > 0 && amount <= balance)
            {
                balance = balance - amount;
                System.out.println("You have withdrawn " + amount + " Rs.");
                System.out.println("New balance is: " + getBalance() + " Rs.");
            }
            else
            {
                System.out.println("Invalid or Insufficient balance for withdrawal");
            }
        }
    }
    
    public class BankApp
    {
        public static void main(String[] args)
        {
            // πŸ‘¨β€πŸ’Ό Creating object
            Account account = new Account();
    
            // 🚫 Cannot access private fields directly
            // account.balance = 10000; // ❌ Not allowed (Encapsulation)
    
            // βœ… Uses public setters and methods
            account.setAccountHolder("Deepak");
    
            // βœ… Proper access via methods ensures validation
            account.deposit(10000);      // Valid deposit
            account.withdraw(3000);      // Valid withdrawal
    
            account.deposit(-20000);     // Invalid deposit
            account.withdraw(100000);    // Invalid withdrawal (insufficient funds)
        }
    }
    Output:
    You have deposited 10000.0 Rs.
    New balance is: 10000.0 Rs.
    You have withdrawn 3000.0 Rs.
    New balance is: 7000.0 Rs.
    Invalid deposit amount
    Invalid or Insufficient balance for withdrawal

Interview Questions :-
  1. What is encapsulation & its use ?
  2. What is Data – Hiding ?
  3. Provide examples of encapsulation in Java.
  4. Difference between Abstraction & Encapsulation ?