What is Encapsulation in Java: Definition and Examples
encapsulation is the practice of hiding the internal details of a class and only exposing necessary parts through methods. It protects data by making fields private and controlling access with public getters and setters.How It Works
Encapsulation works like a protective capsule around the data inside an object. Imagine a capsule medicine that keeps the medicine safe inside and only releases it when needed. Similarly, in Java, the data (variables) inside a class is hidden from outside access by making them private. This means other parts of the program cannot directly change or see these variables.
Instead, the class provides public methods called getters and setters. These methods act like controlled doors that allow safe access to the data. This way, the class controls how its data is used or changed, preventing accidental or harmful modifications.
Example
This example shows a simple class with encapsulation. The age variable is private, and we use methods to get and set its value safely.
public class Person { private int age; // private variable // Getter method to access age public int getAge() { return age; } // Setter method to update age with a check public void setAge(int age) { if (age >= 0) { this.age = age; } else { System.out.println("Age must be non-negative."); } } public static void main(String[] args) { Person p = new Person(); p.setAge(25); // sets age safely System.out.println("Age: " + p.getAge()); p.setAge(-5); // invalid age, will not change System.out.println("Age after invalid set: " + p.getAge()); } }
When to Use
Use encapsulation whenever you want to protect the data inside your classes from being changed unexpectedly. It is especially useful in large programs where many parts interact, helping to avoid bugs caused by improper data changes.
Real-world examples include:
- Bank account classes where balance should not be changed directly.
- Game characters where health or score must be controlled.
- Any class where you want to validate data before saving it.
Key Points
- Encapsulation hides internal data using
privatefields. - Access to data is controlled through
publicgetter and setter methods. - It helps protect data integrity and makes code easier to maintain.
- Encapsulation supports the idea of modular and secure programming.