Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Accessing private fields directly from another instance of the same class

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?

like image 752
Nick Heiner Avatar asked Oct 10 '09 19:10

Nick Heiner


2 Answers

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.

like image 158
dj_segfault Avatar answered Sep 28 '22 10:09

dj_segfault


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.

like image 41
sepp2k Avatar answered Sep 28 '22 10:09

sepp2k