如果一个人想要构造一个不可变的类,不应该公开对非 final 字段的引用 - 但即使是像 Strings 这样的不可变对象?
public final class Test { // Test class is meant to be immutable
private String s; // CAN'T MAKE THIS FINAL
void onCreate(String s) { // a callback called ONCE after construction
this.s = new String(s); // do I need to do this ? (protect me from me)
}
public String getS() {
return new String(s); //do I need to do this ?(protect me from the world)
}
}