Java: Accessing private fields directly from anoth

2019-03-25 06:57发布

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)) {

}

Is this bad practice?

6条回答
Summer. ? 凉城
2楼-- · 2019-03-25 07:34

This is a duplication of

Why can I access my private variables of the "other" object directly, in my equals(Object o) method

Private data is accessible by any instance of that class, even if one instance of class A is accessing the private members of another instance of A. It's important to remember that that access modifiers (private, protected, public) are controlling class access, not instance access

查看更多
太酷不给撩
3楼-- · 2019-03-25 07:35

I tend to always use getters, because sometimes a getter isn't just "return(foo)". Sometimes they initialize things if they're null, or have some debug logging in them, or validate the current state in some way. It's more consistent.

查看更多
Lonely孤独者°
4楼-- · 2019-03-25 07:39

Using private member for entity class may caused proxy class work incorrectly. Imagine hibernate create class by lazy query. If you check member variable , it return null. But if you call get() , it will fetch data from database and initialise the field.

查看更多
ゆ 、 Hurt°
5楼-- · 2019-03-25 07:48

That is fine and completely normal. It is a little bit odd to think that this can fiddle with the private fields of other, but it's okay because there's no way anything bad can happen as far as some third party being able to muck with an Odp object's internals. Any method of the Odp class can modify any private members of any Odp object, even non-this ones, but that's fine since any such methods can obviously be trusted!

查看更多
闹够了就滚
6楼-- · 2019-03-25 07:53

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.

查看更多
祖国的老花朵
7楼-- · 2019-03-25 07:55

I dont think this is bad practice, but a feature of the language. It not only allows you to test equals the way you do, but it is also useful in a Prototype pattern for object creation.

查看更多
登录 后发表回答