Encapsulation: Getters & Setters

Encapsulation: Getters & Setters in Java: Encapsulation is the practice of bundling data (attributes) and methods into a single unit and restricting access to…

Concept Explanation

Encapsulation is the practice of bundling data (attributes) and methods into a single unit and restricting access to the data.

We do this by making attributes private and providing public methods (Getters and Setters) to interact with them. This is like a vending machine: you can't touch the snacks directly, you have to use the buttons (methods).


Syntax or Core Structure

public class Person {
    private String name; // Private data

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

    // Setter (Writable + Secure)
    public void setName(String newName) {
        if (newName != null && !newName.isEmpty()) {
            this.name = newName;
        }
    }
}

Why use this?

  1. Read-Only: Just provide a Getter.
  2. Validation: In the Setter, you can check if a bank withdrawal is too high or an age is negative.
  3. Flexibility: You can change how the data is stored internally without breaking any code that uses the class.

Practice Exercises

  1. The Secure Balance: Create a BankAccount class. Make balance private. Create a deposit() method that only allows positive numbers.
  2. Temperature Converter: Create a class that stores temperature in Celsius (private). Provide a getter that returns it in Fahrenheit.
  3. The Validation Logic: Create a User class with email. In the setEmail method, use .contains("@") to ensure it's a valid format.