N
N
Noortvel2016-10-09 14:41:36
Java
Noortvel, 2016-10-09 14:41:36

Why not a public variable, but get/set functions?

Why is it worth using get/set if the variable can be used in any way?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
V
veydlin, 2016-10-09
@Noortvel

This is called a growth point, you leave the method so that you can then add something to it.
For example, updating some construction after assigning a number more than 10 to a variable, what will you do if the variable is public? Rewrite all the code where it was used?

E
exenza, 2016-10-09
@exenza

Setters often do value checks and validations; in the case of getters, they can combine the values ​​of multiple fields. The logic changes in one place, not many.
Java libraries, such as serialization, and therefore frameworks based on them, use getters and setters

V
Vitaly Vitrenko, 2016-10-09
@Vestail

I highly recommend Joshua Bloch - Effective Java 2nd Edition, Item 14.

R
Rou1997, 2016-10-09
@Rou1997

Not always worth it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question