Creating constructors

All classes have constructors, even if these constructors are just default ones. But what happens when the constructors starts to get bigger and bigger, and harder to maintain? With just two key strokes, we can automatically generate constructors for NetBeans.

Getting ready

Check the recipe Creating a Java Project using Wizard.

Feel free to modify the default settings, but if you wish to follow exactly what we are presenting here, just modify the Project Name to CreatingConstructorsApp and uncheck create main class.

How to do it...

With the project open:

  1. Right-click on the CreatingConstructorsApp project and select New and Java Class....
  2. On the New Java Class window, type Address under Class Name.
  3. Under package, type myclasses.
  4. Click Finish.
  5. When the Address Java Class opens, insert the following code:
    int zipcode;
    int number;
    String street;
    String city;
    
  6. Then press Alt+Insert. A small pop-up will be shown with the title Generate.
How to do it...

Select the first option, which is named Constructor..., then select all four fields, and click on Generate.

How it works...

NetBeans recognizes the fields in the class and generates the constructor based on the fields that were selected.

As best practice, NetBeans names all the constructor fields the same way as the declared variables.

There's more...

What about default constructors? And how to generate multiple constructors?

Default constructor creation

It is also possible to generate default constructors, constructors without any fields, by using this same method.

Simply press Alt+Insert and upon field selection, leave them all unmarked, and click on Generate. A default constructor will then appear inside the class.

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

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