July 2, 2022 • 3 min read
Encapsulation principle

Encapsulation is a fundamental principle of object-oriented programming and software design. It refers to the idea of wrapping data and behavior within a single unit, called an object, in order to hide implementation details and protect the internal state of the object from external modification.

In Java, encapsulation is achieved through the use of classes and access modifiers, such as private, protected, and public. The private access modifier restricts access to a member (field or method) within the class, while the public access modifier allows access from anywhere. The protected access modifier allows access from within the class and its subclasses. The protected modifier also specifies that the member can only be accessed within its own package.

Example

Here is an example of encapsulation in Java:

public class BankAccount {
    private int accountNumber;
    private double balance;

    public BankAccount(int accountNumber) {
        this.accountNumber = accountNumber;
        this.balance = 0;
    }

    public void deposit(double amount) {
        this.balance += amount;
    }

    public void withdraw(double amount) {
        if (amount > balance) {
            throw new IllegalArgumentException("Insufficient funds");
        }
        this.balance -= amount;
    }

    public double getBalance() {
        return balance;
    }
}

In this example, the BankAccount class encapsulates the behavior and data related to a bank account. The accountNumber and balance fields are declared private, meaning they can only be accessed within the BankAccount class. The deposit and withdraw methods allow the user to modify the balance of the account, but enforce certain rules, such as making sure there are sufficient funds before withdrawing. The getBalance method provides a way to retrieve the current balance, but does not allow the balance to be directly modified.

Conclusion

Encapsulation helps to promote good software design by allowing the implementation of an object to change without affecting the rest of the system. It also makes it easier to maintain and debug code, since changes can be made locally within the object, rather than affecting other parts of the system. Additionally, encapsulation makes it possible to hide the complexity of an object's implementation, making the code easier to understand and use.

We use cookies to improve your experience. By using our site, you agree to our use of cookies. Read our Privacy Policy for more information.