Question

In java when I'm writing a class is it recommended to use the getXXX() method or use the variable name using 'this' keyword to refer to the private variables in the same class public methods?

Was it helpful?

Solution

The answer is - it depends.

Yes, I would also recommend that you start by making your variables private, there are cases where this may not be required, but lets stay on subject and only ever allowing access to them via getters

Now assuming your have a public getter for your instance field, this raises the potentially that some one else will want to override this method and change it in some way, maybe return a calculated value based on new values they have introduced or what ever.

If the private field is part of any internal calculation or changes the state of the object logic in some way, then you start having problems, as you are now ignoring the value that is returned by the getter, which would produce undesirable results.

In this case, you must consider the value returned by the getter over the private field.

OTHER TIPS

this.pvtMemberVariable (or) pvtMemberVariable to be used in the same class. Getters are public methods used by the outside classes

Reason for keeping variables private is to hide them from unrequired modification from other classes. However while accessing private variables in its own class, developer is aware of its state. It is feasible to use private members from its own class directly. This will reduce method calls and serve the purpose of privacy.

I think it really depends on your situation. For me, one situation that I often use the getter method is if the variable might not be initialized yet, for example if I am using lazy-initialization. But for most situations, I just reference the variable directly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top