Engineering Full Stack Apps with Java and JavaScript
Encapsulation is the process of wrapping up of data (properties) and behavior (methods) of an object into a single unit; and the unit here is a Class (or interface). Encapsulate in plain English means to enclose or be enclosed in or as if in a capsule. In Java, everything is enclosed within a class or interface, unlike languages such as C and C++ where we can have global variables outside classes.
Encapsulation enables data hiding, hiding irrelevant information from the users of a class and exposing only the relevant details required by the user.
We can expose our operations hiding the details of what is needed to perform that operation.
We can protect the internal state of an object by hiding its attributes from the outside world (by making it private), and then exposing them through setter and getter methods. Now the modifications to the object internals are only controlled through these methods.
Consider the example of a linked list’s getsize method. We might be now using a variable named size that is updated on every insert / delete operation. Later we might decide to traverse the list and find size every time someone ask for size. But if some code was directly accessing the size variable, we would have to change all those code for this change. However if we were accessing the size variable through a getsize method, other code can still call that method and we can do our changes in that method.
Also see http://javajee.com/forum-topic/what-are-setters-and-getters.
Comments
NICE
/*Encapsulate in plain English means to enclose or be enclosed in or as if in a capsule.*/
it's very easy to remeber what is encapsulation :)
That example makes it clear.
That example makes it clear.