Finally, let's take a look at one of the more tedious tasks in Java: implementing the getters and setters for all the fields in our class. With a few fields, there is not much work to be done but with time, classes might grow in size and more fields usually means more getters/setters.
Thanks to NetBeans' refactoring capabilities, this is just as easy as pressing Alt+Insert. Seriously!
Check the recipe Creating a Java Project using Wizard.
Feel free to modify the default settings, but if you wish follow exactly what we are presenting here, just modify the Project Name to CreatingGettersSettersApp and uncheck create main class.
With the project open:
Inside the body of Account.java
, insert:
String firstName; String lastName; String maritalStatus; int id; int accountNumber; long saldo; boolean accountActive;
After the last line of code and before the closing bracket (}), place the cursor and:
NetBeans will then create all the getters and setters for all of the fields that are present in Account.java
.
Are the getters and setters mandatory and is it possible to add those methods later in the game?
It is also possible to regenerate getters and setters if more fields are added to the class.
Try adding a few variables and perform the steps once again when needed.
Also, not all fields will need getters and/or setters, so use them wisely. Some frameworks rely heavily on the usage of get/set pairs, such as Spring and EJB.
18.221.194.44