Skip to main content
Documents
Share
LinkedIn
Facebook
Twitter
Copy
Java keywordsIntroduction To JavaJava File HandlingJava Language BasicsJava ArraysJava Object-Oriented Programming

Java Encapsulation

Encapsulation is a fundamental principle of object-oriented programming (OOP) in Java that involves bundling the data (variables) and the methods (functions) that operate on the data into a single unit, known as a class. It restricts direct access to some of an object's components and can prevent the accidental modification of data.

Purpose of Encapsulation

  • Data Hiding: Encapsulation allows the internal representation of an object to be hidden from the outside. Only the necessary details are exposed through a public interface.
  • Increased Flexibility: By controlling access to the fields of a class, you can change the internal implementation without affecting the external code using the class.
  • Improved Maintainability: Encapsulation helps in maintaining the code by keeping the fields private and providing public getter and setter methods to modify and view the fields.

Implementing Encapsulation in Java

To achieve encapsulation in Java:

  1. Declare the class variables as private.
  2. Provide public getter and setter methods to access and update the value of a private variable.

Example 1: Basic Encapsulation

public class Student {
    private String name;
    private int age;

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

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

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

    // Setter method for age
    public void setAge(int age) {
        if (age > 0) {
            this.age = age;
        }
    }
}

In this example, the Student class has private fields name and age. Public getter and setter methods are provided to access and modify these fields. The setter for age includes a basic validation check.

Example 2: Encapsulation with Validation

public class BankAccount {
    private double balance;

    // Getter method for balance
    public double getBalance() {
        return balance;
    }

    // Setter method for balance with validation
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

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

The BankAccount class encapsulates the balance field. It provides methods deposit and withdraw to modify the balance, ensuring that only valid operations are performed.

Tips and Best Practices

  • Use Private Fields: Always declare class fields as private to protect them from external modification.
  • Provide Access Methods: Use public getter and setter methods to control access to the fields. This allows for validation and flexibility in changing the internal implementation.
  • Validation Logic: Implement validation logic in setter methods to ensure that the object state remains consistent.
  • Immutable Classes: Consider making classes immutable (without setters) if the object state should not change after creation. This enhances security and simplifies concurrent programming.