0
0
Javaprogramming~5 mins

Why encapsulation is required in Java

Choose your learning style9 modes available
Introduction

Encapsulation helps keep data safe and hidden inside an object. It stops other parts of the program from changing data in wrong ways.

When you want to protect important data from accidental changes.
When you want to control how data is accessed or updated.
When you want to make your code easier to fix or improve later.
When you want to hide complex details and show only simple actions.
When you want to group related data and actions together.
Syntax
Java
public class ClassName {
    private DataType variableName;  // hidden data

    public DataType getVariableName() {
        return variableName;       // safe way to read data
    }

    public void setVariableName(DataType value) {
        variableName = value;      // safe way to change data
    }
}

Use private to hide data inside the class.

Use public getter and setter methods to control access.

Examples
This example hides the name and allows safe access through methods.
Java
public class Person {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String newName) {
        name = newName;
    }
}
This example controls how money is added or taken out, protecting the balance.
Java
public class BankAccount {
    private double balance;

    public double getBalance() {
        return balance;
    }

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
        }
    }
}
Sample Program

This program shows how encapsulation protects the speed from being set to a negative value.

Java
public class Car {
    private String model;
    private int speed;

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public int getSpeed() {
        return speed;
    }

    public void setSpeed(int speed) {
        if (speed >= 0) {
            this.speed = speed;
        }
    }

    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.setModel("Sedan");
        myCar.setSpeed(50);
        System.out.println("Model: " + myCar.getModel());
        System.out.println("Speed: " + myCar.getSpeed());

        myCar.setSpeed(-10);  // This will not change speed because of check
        System.out.println("Speed after invalid update: " + myCar.getSpeed());
    }
}
OutputSuccess
Important Notes

Encapsulation helps avoid bugs by controlling how data changes.

It makes your code easier to understand and maintain.

Always use getter and setter methods to access private data.

Summary

Encapsulation hides data to keep it safe.

It uses private variables and public methods.

This helps control and protect how data is used.