Encapsulation is an OOP principle that combines data and the methods that operate on that data within a single class while restricting direct access to the internal state of the object. It helps protect data and ensures controlled access through public methods.
Key Points: • Encapsulation promotes data hiding by declaring fields as private. • Access to private data is provided through public getter and setter methods. • It improves security by preventing unauthorized modification of data. • Encapsulation makes code easier to maintain and modify. • It helps achieve loose coupling and better control over object behavior.
Example: In a banking application, the account balance should not be directly accessible from outside the class. Instead, it should be accessed and modified through dedicated methods to ensure valid operations.
Code Example:
public class Employee {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}Interview Tip: A concise interview answer is:
"Encapsulation is the process of wrapping data and methods into a single unit and restricting direct access to the data. In Java, it is achieved by making variables private and providing public getter and setter methods to access them."