Interviewer: What is encapsulation and how do you achieve it in Java?
Me: Encapsulation is a mechanism to hide
Data hiding means we are providing security to data within the class.
Abstraction means hiding the code by defining member functions.
Encapsulation is the combination of abstraction and data hiding, means we are wrapping data and code associated with that data. For ex bean class
class student {
private int age; // Data Hiding
public setAge(){} // Abstraction
public getAge(){} // Abstraction
}
student class is encapsulated.
encapsulation = data hiding + abstraction