类方法如何访问同一类的另一个实例的私有成员? [英] How can a class method access a private member of another instance of the same class?

查看:68
本文介绍了类方法如何访问同一类的另一个实例的私有成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看不懂 jdk1.7 中的代码.value 是私有的,那么为什么代码可以使用它,例如anotherString.value?

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;

    //.....
}

推荐答案

因为私有是为了保护您的代码免受其他程序员(包括您未来的自己)的侵害,而不是保护实例免受其他实例的侵害.

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

如果您正在为类本身编写代码,那么您使用您的"实例的值做坏事的风险与使用其他"实例的值做的事情的风险一样大,因为它们都是同类型.所以对后者施加更大的限制是没有意义的.另一方面,如果您在另一个类中编写代码,则假定您对 String 的内部结构不够熟悉,无法正确使用私有字段.

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.

这篇关于类方法如何访问同一类的另一个实例的私有成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆