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?
- Read-Only: Just provide a Getter.
- Validation: In the Setter, you can check if a bank withdrawal is too high or an age is negative.
- Flexibility: You can change how the data is stored internally without breaking any code that uses the class.
Practice Exercises
- The Secure Balance: Create a
BankAccountclass. Makebalanceprivate. Create adeposit()method that only allows positive numbers. - Temperature Converter: Create a class that stores temperature in
Celsius(private). Provide a getter that returns it inFahrenheit. - The Validation Logic: Create a
Userclass withemail. In thesetEmailmethod, use.contains("@")to ensure it's a valid format.