简体   繁体   English

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

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

I cannot understand the code in jdk1.7. 我无法理解jdk1.7中的代码。 value is private, so why can the code use it with eg anotherString.value ? 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;

    //.....
}

Because private is for protecting your code from other programmers (including your future self), not for protecting instances from other instances. 因为private是为了保护您的代码不受其他程序员(包括您将来的自己)的侵害,而不是保护实例免受其他实例的侵害。

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. 另一方面,如果您要在另一个类中编写代码,则假定您不熟悉-足够熟悉String的内部结构才能正确使用私有字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM