I can't understand the use of getter and setters? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

I can't understand the use of getter and setters?

Firstly we are making a variable private so that no one can access it and than using getters and setters to give its access to everyone why is it so ?? If we want to access it than why we don't make it public why we are making it private and using getters and setters??

3rd Sep 2017, 5:20 AM
Vaibhav Singh Sikarwar
Vaibhav Singh Sikarwar - avatar
5 Answers
+ 3
I think everybody ask themselves the same question when they are learning this subject. Getters and setters gave us more control over the variables. Suppose that you write a program that only allows positive values or non cero values. You can define a setter that alert your user when they try to input a wrong number and prevent the software to crash.
4th Sep 2017, 5:32 AM
Andres Restrepo
Andres Restrepo - avatar
+ 4
It's all about the first principle of OOP - incapsultion! If there were no encapsulation, no access modifiers then there would be no need in getters and setters! Try reading the basics of OOP! Herbert Schildt and Java complete reference will help you!
3rd Sep 2017, 8:19 AM
Val🐯
Val🐯 - avatar
+ 3
Get helps you scour the place for that value. Set helps you change its value. Hope I am right
3rd Sep 2017, 6:15 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
0
It his not useful to automatically create getters and setters. Only when at least one of them contains custom code, is it useful. You also can create immutable objects that never change once created by declaring all fields final. Then you never need getters and settters.
3rd Sep 2017, 10:58 AM
1of3
1of3 - avatar