This may be a general question, but I could not find anything good for him. I'm trying to figure encapsulation of reference variablesin Java.
In the code below:
class Special {
private StringBuilder s = new StringBuilder("bob");
StringBuilder getName() { return s; }
void printName() { System.out.println(s); }
}
public class TestSpecial {
public static void main (String[] args ) {
Special sp = new Special();
StringBuilder s2 = sp.getName();
s2.append("fred");
sp.printName();
}
}
Result: bobfred
At first I thought about creating our field privateand provided a method getter, this is a good encapsulation method. But when I looked at it in more detail, I saw that when I call getName(), I really return a copy, as always. But I do not return a copy of the object StringBuilder. I am returning a copy of the reference variable pointing to a single object StringBuilder. So, at the moment when it returns getName(), I have one object StringBuilderand two reference variables pointing to it (s and s2).
, ? :). .