class 方法如何访问同一个 class 的另一个实例的私有成员?

How can a class method access a private member of another instance of the same class?

我看不懂jdk1.7的代码。 value 是私有的,那么为什么代码可以将它用于例如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;

    //.....
}

因为 private 是为了保护你的代码不受其他程序员(包括你未来的自己)的影响,而不是为了保护实例不受其他实例的影响。

如果您正在为 class 本身编写代码,那么使用 "your" 实例的值做坏事的风险与使用 [=15] 的值一样大=] 实例,因为它们都是同一类型。因此,对后者施加更大的限制是没有意义的。另一方面,如果您在另一个 class 中编写代码,则假设您对 String 的内部结构不够熟悉,无法正确使用私有字段。