Java Encapsulation


What is Encapsulation in Java

Encapsulation is a fundamental concept of Object-Oriented Programming in Java. It means combining variables and methods into a single unit called a class. The key idea is to keep the internal details of an object hidden from the outside world. In other words, encapsulation allows you to protect the data and expose only what is necessary through controlled methods.

In Java, encapsulation is achieved by declaring class variables as private and providing public getter and setter methods to access and modify them. This ensures that the internal state of an object cannot be changed directly.

Why Use Encapsulation in Java

Encapsulation is important because it secures data and helps in maintaining control over how it’s used. When variables are kept private, they cannot be accessed or modified directly by outside classes.

For example, in a banking application, users should not be allowed to change their balance directly. Instead, they should only be able to deposit or withdraw money using specific methods. This prevents errors and maintains data integrity.

Encapsulation also helps in writing cleaner, maintainable, and flexible code that can be easily modified later without affecting other parts of the program.

How to Achieve Encapsulation in Java

Encapsulation in Java can be achieved through the following steps:

  1. Declare all class variables as private.

  2. Provide public getter methods to read the variable’s value.

  3. Provide public setter methods to modify the variable’s value.

  4. Use these getter and setter methods in your main program instead of accessing variables directly.

This gives full control over how data is accessed and updated inside a class.

Example of Encapsulation in Java

class Student {
    // private variables
    private String name;
    private int age;

    // getter for name
    public String getName() {
        return name;
    }

    // setter for name
    public void setName(String name) {
        this.name = name;
    }

    // getter for age
    public int getAge() {
        return age;
    }

    // setter for age with validation
    public void setAge(int age) {
        if(age > 0) {
            this.age = age;
        } else {
            System.out.println("Age must be greater than 0");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.setName("Ananya");
        s1.setAge(20);

        System.out.println("Student Name: " + s1.getName());
        System.out.println("Student Age: " + s1.getAge());
    }
}

Explanation:
Here, name and age are private variables that cannot be accessed directly. The getName() and getAge() methods allow reading values, while setName() and setAge() allow updating them with proper validation.

Real-Life Example of Encapsulation

Think of a coffee machine. You only press buttons to make coffee, but you have no access to its internal wiring or brewing process. The machine hides its complex mechanism and provides only a simple interface for you to use.

Encapsulation works the same way in Java — it hides the internal data and only exposes the methods needed for interaction.

Example with Validation in Java

class BankAccount {
    private double balance;

    public double getBalance() {
        return balance;
    }

    public void deposit(double amount) {
        if(amount > 0) {
            balance += amount;
            System.out.println("Deposited: " + amount);
        } else {
            System.out.println("Deposit amount must be positive.");
        }
    }

    public void withdraw(double amount) {
        if(amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("Withdrawn: " + amount);
        } else {
            System.out.println("Invalid or insufficient balance.");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount acc = new BankAccount();
        acc.deposit(5000);
        acc.withdraw(2000);
        System.out.println("Current Balance: " + acc.getBalance());
    }
}

Explanation:
In this example, the balance variable is private. Users can only deposit or withdraw using the provided methods. This prevents direct and unsafe modification of data, keeping the system secure.

Difference Between Encapsulation and Abstraction

Feature Encapsulation Abstraction
Definition Hides data by restricting access to variables Hides implementation details and focuses on essential features
Purpose Data protection Simplifying code complexity
Achieved By Private variables with getter/setter methods Abstract classes and interfaces
Focus How data is accessed What operations are performed

Both encapsulation and abstraction are related but serve different purposes. Encapsulation is about data security, while abstraction is about simplifying functionality.

Advantages of Encapsulation

  1. Data Security: Prevents unauthorized access to internal data.

  2. Validation Control: Allows adding validation logic in setters.

  3. Easier Maintenance: Internal implementation can be changed without affecting other parts of the program.

  4. Improved Modularity: Each class manages its own data and behavior.

  5. Better Code Reusability: Classes become independent and reusable.

Key Points About Java Encapsulation

  • Declare variables as private.

  • Use getter and setter methods for data access.

  • Always validate inputs in setter methods.

  • Keep the class logic hidden and expose only what’s required.

  • Encapsulation helps in writing secure and modular programs.

Summary of the Tutorial

Encapsulation in Java is about keeping your data safe by restricting direct access to class variables. It allows you to manage how data is accessed and updated using getters and setters. This makes the code secure, flexible, and easier to maintain. It’s one of the key features of Object-Oriented Programming that improves code quality and ensures data integrity.


Practice Questions

  1. Create a class Employee with private variables name, salary, and department. Write getter and setter methods to access and update these values safely.

  2. Write a Java program that uses encapsulation to store and validate a student’s roll number and marks. The marks should not be negative or greater than 100.

  3. Create a class Book that contains private fields title, author, and price. Implement methods to set and get these values. Add validation so that the price cannot be less than zero.

  4. Write a Java program to demonstrate how encapsulation prevents direct access to class data by making all data members private and providing public methods.

  5. Create a class BankAccount that allows users to deposit and withdraw money through encapsulated methods. Prevent withdrawals if the balance is insufficient.

  6. Develop a program where a class Laptop has private data members like brand, ramSize, and price. Write setter methods that check valid RAM size and positive price before assigning values.

  7. Write a program that defines a class Car with private variables speed and fuel. Add setter methods that prevent setting speed beyond 180 km/h and fuel beyond 60 liters.

  8. Create a class Patient with private variables name, age, and weight. Add validation in setters so that the age and weight cannot be negative. Display all patient details using getter methods.

  9. Implement a Java class UserAccount with private fields username and password. Provide public methods to set and verify credentials. Do not allow empty or null values.

  10. Write a Java program using encapsulation to define a class Temperature that stores temperature in Celsius. Provide methods to convert it to Fahrenheit and Kelvin while keeping the Celsius value private.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top