Question about getter and setter methods in Java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Question about getter and setter methods in Java

hi everyone. I wish to clarify some things and hopefully you can tell me if some of the things I have right or got wrong in terms of facts. Here goes. In java we can either have a setter or getter method. getter methods are used for retrieving variable values while setters can be used to manipulate or rather reset a variables value since those methods are the receivers while getters are the senders. forgive me if I got nothing right. I just want to learn from my misunderstandings lol.

28th Jul 2017, 7:52 PM
YodaCoda
YodaCoda - avatar
4 Answers
+ 1
@Din It's not recommended. Take a look: private int age; void setAge (int age){this.age = age;} int getAge (){return this.age;} Did you notice something? The getter method doesn't require an argument, but returns a value. The setter method in the other hand does require an argument (to assign it to a variable, the class field). Now: is it possible to have a function that works both as getter and setter? Yes, it is. But you'll gave more headache to deal with, and the usability of your code will be impacted
28th Jul 2017, 9:22 PM
Tiago Soares
Tiago Soares - avatar
+ 2
Man, you're not wrong. I want to point it out that getters and setters are very powerful: First they protect the class fields (encapsulation): you can keep those variables private then nobody can change in an unexpected way. If you need that value you call a getter instead. Other thing is you can impose restrictions to assign a value. For example, you're coding a program for a bar (in this place only grown-ups are allowed). You create a class Person (it will hold the bar clients) with a field called age (int age). If you have a setter for age you can restrict ages bellow 18, for instance. If you didn't have a setter, someone could enter an age 12... Other greatest advantage is: I write my code and I don't have to worry if others know how my class fields are. I just have the getters and setters, protecting them and at same time with restrictions to my program work in an expected way
28th Jul 2017, 8:15 PM
Tiago Soares
Tiago Soares - avatar
+ 2
wow thanks for that explanation. getters and setters are really cool.
28th Jul 2017, 8:18 PM
YodaCoda
YodaCoda - avatar
+ 1
quick question can a method be both a getter and a setter or only one?
28th Jul 2017, 8:44 PM
YodaCoda
YodaCoda - avatar