Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

java - is getter method call to access variable better than direct variable access within a 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...