I cannot understand the code in jdk1.7. value
is private, so why can the code use it with e.g. anotherString.value
?
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;//cannot understand
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
//.....
}
Because private is for protecting your code from other programmers (including your future self), not for protecting instances from other instances.
If you're writing code for the class itself, you have as much risk of doing something bad with the value of "your" instance as you do with the value of the "other" instance, since they're both the same type. So there's no sense in imposing greater constraints on the latter. On the other hand, if you're writing code in another class, it's assumed you're not going to be familiar-enough with the internals of String to use the private field properly.