我无法理解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 是为了保护您的代码免受其他程序员(包括未来的您)的影响,而不是为了保护实例免受其他实例的影响。
如果您正在为类本身编写代码,那么您对“您的”实例的值做坏事的风险与对“其他”实例的值做坏事的风险一样大,因为它们都是相同的类型。因此,对后者施加更大的限制是没有意义的。另一方面,如果您在另一个类中编写代码,则假定您对 String 的内部结构不够熟悉,无法正确使用私有字段。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)