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 .