Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain to me what is a setter and getter

Tags:

oop

What are setters and getters? Why do I need them? What is a good example of them in use in an effective way? What is the point of a setter and getter?

Update: Can I get some coding examples please?

like image 319
Strawberry Avatar asked Apr 15 '10 21:04

Strawberry


People also ask

How does a setter work?

Starting PositionIn the front row, the setter blocks on the right side. They are responsible for blocking against the other team's left side or outside hitter. In the back row, the setter plays right back and is responsible for digging if necessary and getting up to the net quickly to set if they do not make the dig.

What can I use instead of getters and setters?

You may use lombok - to manually avoid getter and setter method. But it create by itself. The using of lombok significantly reduces a lot number of code. I found it pretty fine and easy to use.

How does getter and setter work in Java?

Getter returns the value (accessors), it returns the value of data type int, String, double, float, etc. For the program's convenience, getter starts with the word “get” followed by the variable name. While Setter sets or updates the value (mutators). It sets the value for any variable used in a class's programs.


1 Answers

A getter/setter is used to hide a private field from the publicity (you can avoid direct access to a field).

The getter allows you to check a provided value before you use it in your internal field. The setter allows you for instance to apply a different format or just to restrict write access (e.g. to derived classes).

A useful application of a getter can be some kind of lazy loading: The backing field (the private field that is hidden by the getter) is initialized to null. When you ask the getter to return the value, it will check for null and load the value with a more time consuming method. This will happen only the first call, later the getter will provide the already loaded value all the time.

like image 132
tanascius Avatar answered Sep 23 '22 17:09

tanascius