Java Encapsulation

Learn Encapsulation in Java. Understand data hiding, getters, setters, and how to protect your data from unauthorized access.

Encapsulation is one of the four fundamental OOP concepts. It refers to bundling data (variables) and methods (functions) together into a single unit (class) and restricting direct access to some of an object's components.

Think of a Capsule (Medicine) 💊.

  • The medicine is hidden inside the capsule.
  • You can't touch the medicine directly; you swallow the capsule.

In Java, we achieve encapsulation by:

  1. Declaring variables as private.
  2. Providing public getter and setter methods to access/modify them.

Why Encapsulation? (Data Hiding)

Imagine a Bank Account. If your balance variable is public, anyone can set it to -1000000 or 99999999.

class BankAccount {
    public double balance; // BAD! Anyone can change this directly.
}

With encapsulation, we make balance private and control how it changes.

class BankAccount {
    private double balance; // Good! Hidden from outside.

    // Getter (Read-only access)
    public double getBalance() {
        return balance;
    }

    // Setter (Write access with validation)
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        } else {
            System.out.println("Invalid amount!");
        }
    }
}

Tip 💡: Encapsulation gives you control. You decide who can read (getter) and who can write (setter) your data. You can even make variables read-only by not providing a setter!

Getters and Setters

  • Getter: Returns the value of a private variable.
  • Setter: Sets the value of a private variable (often with validation logic).

Example: Person Class

class Person {
    // Private variable
    private int age;

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

    // Setter method
    public void setAge(int age) {
        if (age > 0 && age < 120) {
            this.age = age;
        } else {
            System.out.println("Please enter a valid age.");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Person p = new Person();

        // p.age = -5; // Error! age is private

        p.setAge(25); // Valid
        System.out.println("Age: " + p.getAge());

        p.setAge(-5); // Invalid, validation blocks it
    }
}

Benefits of Encapsulation

  1. Data Hiding: Users have no idea how the class stores data internally.
  2. Increased Flexibility: You can make variables read-only or write-only.
  3. Reusability: Encapsulated code is easier to reuse.
  4. Testing Code: It's easier to test encapsulated code.

How do you achieve data hiding in Java?

/>


Immutable Classes

An immutable class is a class whose objects cannot be modified after they are created. String and Wrapper classes (like Integer, Double) are examples of immutable classes.

To create a custom immutable class:

  1. Declare the class as final so it can't be extended.
  2. Make all fields private and final.
  3. Initialize fields via a constructor.
  4. Provide only getters (no setters).
final class ImmutablePerson {
    private final String name;
    private final int age;

    public ImmutablePerson(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() { return name; }
    public int getAge() { return age; }
}

Note : Java is a statically-typed language. It means that all variables must be declared before they can be used.

Challenge

Complete this chapter to unlock the next one.

Challenge

Task:

Create a class 'User' with a private String 'password'. Add a method 'setPassword(String p)' that only updates password if length > 5.

Key Takeaways

  • Data Hiding: Mark fields as private.
  • Accessors: Use public getters and setters.
  • Control: Add validation logic inside setters to protect data.

Common Pitfalls

[!WARNING] Public Fields: Never make fields public unless they are constants (static final).

Blind Setters: Don't just create a setter for every field. If a field shouldn't change (like id), don't make a setter!

What's Next?

What if we want to define a template but force children to fill in the details? Learn Abstract Classes →