Java:直接从同一个类的另一个实例访问私有字段 [英] Java: Accessing private fields directly from another instance of the same class

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

问题描述

我正在为一个类编写一个 equals(Object obj)函数。我看到可以从调用者访问 obj 的私有字段。所以不要使用getter:

I'm writing a equals(Object obj) function for a class. I see that it is possible to access the private fields of obj from the caller. So instead of using a getter:

Odp other = (Odp) obj;
if (! other.getCollection().contains(ftw)) {

}

我可以直接访问该字段:

I can just access the field directly:

Odp other = (Odp) obj;
if (! other.collection.contains(ftw)) {

}

这是不好的做法吗?

推荐答案

不,不是。私有变量和方法无法从其他类访问的原因是允许您更改类的内部,而无需更改使用该类的所有代码(并且防止类的用户例如设置变量)一个它从未应该具有的值。)

No, it's not. The reason that private variables and methods are not accessable from other classes is to allow you to change the internals of your class without having to change all the code that uses the class (that and to prevent the user of your class from e.g. setting a variable to a value that it's never supposed to have).

如果你使用其他对象的私有变量不会伤害任何东西,因为如果你重组你的类的内部,无论如何你必须改变类中的代码。

If you use private variables of other objects that doesn't hurt anything, because if you'd restructure your class's internals, you'd have to change the code inside the class anyway.

这篇关于Java:直接从同一个类的另一个实例访问私有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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