Private variable java question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Private variable java question

what is the use of private variable when we can use getter and setter to alter variable info?

21st Oct 2017, 10:53 PM
oyl
4 Answers
+ 3
When you use a private variable it doesn't have getters and setter by default you're the one who code those methods so you can avoid the setter and *bum* you can't alter the variable!
22nd Oct 2017, 3:26 AM
Chriptus13
Chriptus13 - avatar
+ 2
@oyl it's more of a good practice, like you could make your setter check if the value you're trying to enter is valid for that variable otherwise when you have a public variable you just change it with the wrong value and that can ruin your code!
22nd Oct 2017, 1:01 PM
Chriptus13
Chriptus13 - avatar
+ 1
@André Martins if you want to alter at the first place.why dont you just use public?why do u have to block your own access and then allowing it again.
22nd Oct 2017, 5:03 AM
oyl
0
@André Martins how do u use setter to check?can you provide an example.sorry for asking so many questions.i really want to improve
22nd Oct 2017, 2:25 PM
oyl