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

时间:2015-03-16 00:56:26

标签: java private

我无法理解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;

    //.....
}

1 个答案:

答案 0 :(得分:4)

因为私有用于保护您的代码免受其他程序员(包括您未来的自己)的攻击,而不是用于保护实例免受其他实例的攻击。

如果您正在为课程本身编写代码,那么您可能会因为&#34;您的&#34;实例,就像你对&#34;其他&#34;的价值所做的那样。例如,因为它们都是相同的类型。因此,对后者施加更大限制是没有意义的。另一方面,如果您正在另一个类中编写代码,那么它假设您不会熟悉String的内部,以便正确使用私有字段。