In response to What is your longest-held programming assumption that turned out to be incorrect? question, one of the wrong assumptions was:
That private member variables were private to the instance and not the class.
(Link)
I couldn't catch what he's talking about, can anyone explain what is the wrong/right about that with an example?
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. Another way to think about encapsulation is, that it is a protective shield that prevents the data from being accessed by the code outside this shield.
Encapsulation in Java is the process by which data (variables) and the code that acts upon them (methods) are integrated as a single unit. By encapsulating a class's variables, other classes cannot access them, and only the methods of the class can access them.
Which among the following best describes encapsulation? Explanation: It is a way of combining both data members and member functions, which operate on those data members, into a single unit.
Encapsulation is used to hide the values or state of a structured data object inside a class, preventing direct access to them by clients in a way that could expose hidden implementation details or violate state invariance maintained by the methods.
public class Example {
private int a;
public int getOtherA(Example other) {
return other.a;
}
}
Like this. As you can see private doesn't protect the instance member from being accessed by another instance.
BTW, this is not all bad as long as you are a bit careful. If private wouldn't work like in the above example, it would be cumbersome to write equals() and other such methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With