Generating getters and setters

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!

Getting ready

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.

How to do it...

With the project open:

  1. Right-click on the CreatingGettersSettersApp project and select New and Java Class....
  2. On the New Java Class window, type Account under Class Name.
  3. Under package, type myclasses.
  4. And click Finish.

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:

  1. Press Alt+Insert.
  2. Select Getter and setter....
  3. Select the uppermost checkbox that says Account.
  4. Click on Generate.

NetBeans will then create all the getters and setters for all of the fields that are present in Account.java.

There's more...

Are the getters and setters mandatory and is it possible to add those methods later in the game?

Addition of newer get/set methods

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.194.44