我无法理解jdk1.7中的代码。 value
是私有(private)的,那么为什么代码可以使用它,例如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)是为了保护您的代码免受其他程序员(包括 future 的您)的侵害,而不是为了保护实例免受其他实例的侵害。
如果您正在为类本身编写代码,那么您对“您的”实例的值做坏事的风险与对“其他”实例的值做坏事的风险一样大,因为它们都是相同类型。因此,对后者施加更大的限制是没有意义的。另一方面,如果您在另一个类中编写代码,则假定您对 String 的内部结构不够熟悉,无法正确使用私有(private)字段。
关于java - 类方法如何访问同一类的另一个实例的私有(private)成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29068114/