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

拥有回忆 提交于 2019-12-24 02:07:40

问题


I cannot understand the code in jdk1.7. value is private, so why can the code use it with e.g. 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:


Because private is for protecting your code from other programmers (including your future self), not for protecting instances from other instances.

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.



来源:https://stackoverflow.com/questions/29068114/how-can-a-class-method-access-a-private-member-of-another-instance-of-the-same-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!