Encapsulation
Encapsulation means bundling an object's data (fields) together with the methods that operate on that data, while restricting direct outside access to the data itself.
1. What is Encapsulation?
Encapsulation means bundling an object's data (fields) together with the methods that operate on that data, while restricting direct outside access to the data itself. In Java, this is usually done by making fields private and providing public getter and setter methods to access them.
2. Why is it used?
Encapsulation protects an object's data from being changed incorrectly from outside the class. For example, a setter method can include validation logic (like rejecting a negative age), something direct field access wouldn't allow.
3. Real-Life Example
Think of a medicine capsule, which safely wraps the actual medicine inside a protective shell. You interact with the capsule as a whole, not by directly touching the raw medicine inside — encapsulation protects an object's internal data the same way.
4. Syntax
javaclass ClassName { private dataType fieldName; public dataType getFieldName() { return fieldName; } public void setFieldName(dataType value) { fieldName = value; } }
5. Example Program
javaclass Account { private double balance; public double getBalance() { return balance; } public void setBalance(double amount) { if (amount >= 0) { balance = amount; } } } public class EncapsulationDemo { public static void main(String[] args) { Account acc = new Account(); acc.setBalance(5000); System.out.println("Balance: " + acc.getBalance()); } }
Output:
Balance: 5000.06. Key Points to Remember
- Fields are usually kept
private; access is provided only through public getters and setters. - Encapsulation allows adding validation logic inside setters, protecting data integrity.
- It's one of the four main pillars of Object-Oriented Programming, along with Inheritance, Polymorphism, and Abstraction.