private
in Java
provides class level encapsulation. Is it possible to encapsulate an object instead? Or is this futile to do so?
For instance if we define a class as,
public class Person {
private String ssn;
private ArrayList<Person> friends = new ArrayList<Person>();
public void addFriend (Person stranger) {
friends.add(stranger);
// but here I have access to her ssn
System.out.println(stranger.ssn);
}
}
How would I shield access to ssn
of stranger
in the method addFriend()
above when I require that the stranger
's object be passed to it as parameter?
Java doesn't have an "instance" private access modifier, ie. where you can restrict access only to this
instance's fields/methods.
And you probably don't need one. You're in your Person
class. You're the developer. What do you need to hide from yourself?