Suppose you have a relatively large class file consisting of 20 or more fields. How long will it take you to write getters and setters so that these fields may be accessed by other classes? Even a fast typist will consider this to be a very tedious task. Isn’t there some way to do this faster? Or perhaps automatically…? Alas, Eclipse can do it for us.
In this example, I will only display 2 fields for the sake of simplicity. If this were a real life example, I would simply write the methods myself. But if I had many more fields, I would certainly take advantage of this time-saving feature.
With your class file open, go to Source -> Generate Getters and Setters… from the menu.
Select which fields you want to generate getters and setters for. In this case, we will choose both fields. You also have options for setting the access modifiers. In this case we will choose public. Click OK.
There you have it
The fields we chose now have getters and setters, and it only took a few seconds to do. This will probably shave you off a few minutes of tedious programming.
