Interviewer: What is encapsulation and how do you achieve it in Java?
Me: Encapsulation is a mechanism to hide
Encapsulation: Encapsulation is one of the pillar of OOPS, also is superset for the other two terms, data hiding and abstraction. (Data hiding, as the term refers.. Data can only be stored in variables. To hide the data from external world we use data hiding concept. Public, Private, Protected these are three access modifiers provided to us for data hiding. Default is limited to package. Protected limited to inherited class.) ** Private variables are accessible only inside class which means if there is an inner class, there also private variables could be called directly. Only Static Inner Classes can call Static Variables.
Now coming to Abstraction (meaning Intangible). Abstraction is also considered as the process to hide the implementation from user and provide only final result. Example: we have a person class which has “Weight” property. This property is quite tricky because we cannot accept less than 0 weight for a person. Also we cannot accept more than 500 kgs. So hiding the implementation for these will be in the setter method. This thing hiding the implementation details is Abstraction.
** And the Complete Package i.e. making the object private and implementation of logic in setter and getter is called ENCAPSULATION.