Java, Software Development

Java – Create class constructor with fields faster in Eclipse

This post shows how to create a Java class constructor with fields faster in Eclipse. Before the advent of smart IDEs, Java developers write out almost all codes as it was the only way to do and IDEs were in their infancy. Then, fast forward to now! We have Eclipse, and IntelliJ to name a few.

Java Class with many fields

Consider the following Java class with many fields. Although not typical in small applications, such classes do exist, especially in large programs.

The Java class has twenty instance variables that we may need to initialize. Back in the day, we would write the getter and settings method one by one. Meanwhile, if we needed a constructor that accepts many fields, we would write out the arguments for the constructor.

Use Eclipse to generate Java class constructors with fields

For this post, we use Eclipse. However, we could use the same principle in IntelliJ or other smart IDEs. First, we need to have Eclipse running and create a Java class with many fields. Then, right-click anywhere in the source code file and choose Source. Next, choose Generate Constructor using Fields... option, as shown below.


Then, a window will display from which you can select the fields you wish to include in the constructor.


Finally, click OK. Imagine doing this manually!

Eclipse Creates a Java Constructor

When we go back to our Java class, we can see a new constructor with selected fields.

There are many other similar features Eclipse has. For example, Eclipse can generate hashCode and equals methods. The same goes for other smart IDEs.


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like