+ 1
can ny1 explain what is encapsulation in easy way???
3 Respuestas
+ 3
Encapsulation is access restriction to some class members from the outside.
Typically, you will set access of attributes to private and, if needed, provide public methods to get their value (getters) or change them (setters).
Hiding the implementation of your class allows you to change it at any time without worrying about breaking code using your class.
It is also useful to prevent outside code from changing the state of an object to an incoherent one. For example, let's say you have a class to handle some sort of linked list, with an attribute length indicating the length of that list. If length could be modified from outside, it could be set to an arbitrary number that would not correspond to the number of elements in the linked list. Restricting access to private and letting the methods of the class handle the attribute (when an element is added or removed from the list) prevents this.
You can also provide a getter but no setter to make an attribute essentially read-only for a given state, which could be useful for length in our previous example.
+ 2
think of a security fence
public is no fence and everyone can get in
private is when only what's inside can access it
0
Think of a bank teller.When he opens up your file, he needs your ID, and only he can access your particular data from the terminal.So your data, John's data, and Harry's data are encapsulated in the code, and a guy cant just walk off he street into the bank and get your account data by saying he is you, or screwing around the public info computer.