Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is getter method call to access variable better than direct variable access within a class

Tags:

java

class

I am just curious to know if it advisable within a class instance to access the class variables using getter methods and if there are any tangible performance differences with direct access. Especially in situations where many objects are expected to be generated in the jvm.

like image 595
Bwire Avatar asked May 16 '14 13:05

Bwire


1 Answers

In Java it is a convention to access all fields via getter/setters from outside the class. From inside the class, you usually access fields directly. However, you can also access them via getter/setter is you want to.

It is important to know that this is just a convention. Many other programming languages don't have such strict rules or other concepts. So you are not forced to do that. But it is a good practice.

And: Don't mind performance! Using getters/setters will not affect the performance of your app. The JVM/Java is designed to work exactly like this. Every JVM will optimize your code and handle getters/setters in a very effective way. Try to write clear and good readable code.

like image 89
Thomas Uhrig Avatar answered Sep 30 '22 10:09

Thomas Uhrig