The following code illustrates the situation:
class Human {
private String heart = "default heart";
public void control(Human h) {
h.heart = "$%^&*@@!#^";
}
public String getHeart() {
return heart;
}
}
public class HumanTest {
public static void main(String[] args) {
Human deb = new Human();
Human kate = new Human();
System.out.println(deb.getHeart());
kate.control(deb);
System.out.println(deb.getHeart());
}
}
Here heart [private variable] of deb got modified unfortunately. 🙂
Java allows the code to run without any error.But is it justified to give a object the privilege to access private member of other object even if the code is in the same class ?
Shouldn’t Java disallow this?
As I know, private means restricting access beyond the class source code. But the same concept is applied in the source code above. and the result is disastrous since a person’s heart can’t be modified by any random person .
If the result is disastrous, you shouldn’t code the class so that it allows it. The “bug” is not caused by code external to the class, but by code of the class itself. So it’s simply a bug in your code.
If Java did not allow it, you could only compare objects of the same class by their public attributes, for example, which would either break encapsulation (by exposing private stuff), and/or be very slow (by forcing to make defensive copies of the private attributes to make them available to other objects.