Back to course

OOP Pillar 1: Encapsulation (Access Modifiers: public, private)

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 18: OOP Pillar 1: Encapsulation

Encapsulation is the mechanism of wrapping the data (variables) and the code acting on the data (methods) together into a single unit (the class). It involves restricting direct access to components.

The Principle of Data Hiding

We achieve encapsulation primarily through access modifiers, which control visibility and accessibility.

Access Modifiers in Java

ModifierVisible within ClassVisible within PackageVisible outside Package (Subclass)Visible Everywhere
privateYesNoNoNo
(Default/Package)YesYesNoNo
protectedYesYesYesNo
publicYesYesYesYes

Implementing Encapsulation

The standard practice is to declare all instance variables as private to hide the internal data and prevent unauthorized modification.

java public class Account { // Data is hidden (private) private double balance = 0.0;

// This method is the only way to change the balance
public void deposit(double amount) {
    if (amount > 0) {
        balance += amount;
        System.out.println("Deposit successful.");
    } else {
        System.out.println("Deposit amount must be positive.");
    }
}

// Method to read the data
public double getBalance() {
    return balance;
}

}

// Usage example: Account myAccount = new Account(); // myAccount.balance = -100; // ERROR! Cannot access private field myAccount.deposit(500.0); // OK, access controlled by deposit method

Benefit: Encapsulation allows us to maintain control over the object's state, validate input, and change the internal implementation without affecting the external code that uses the class.