Eclipse IDE – How to generate constructor using fields ?

In this article, we will discuss how to generate constructor with fields for a Java class

1. Earlier era:

  • Often for any POJO, writing constructor is very important
  • Which is used during Object instantiation, thus supplying initial values for object construction
  • Depending on the business requirement, mentioning different parameterized constructor is also important
  • Everyone has to write/code different parameterized constructor on plain text file (file name ending with extension .java)

2. IDE era (Eclipse or IntelliJ or NetBeans):

  • With the release of IDE by various vendors helped developer in a long way to write/code only important business logics
  • With IDE, generating getter/setter, constructor, renaming, refactoring, etc. becomes very easy
  • With Eclipse IDE, writing/coding different parameterized constructor is very easy within few shortcut keys and it has Menu to navigate through (rather it is called generating)
  • There are similar shortcut keys available in all other leading IDE like NetBeans, IntelliJ, etc.

3. Generate constructor with fields in Eclipse IDE:

Step 1: Create a POJO with 4 member variables

Step 2: Generate Constructor with fields

Right-click on the Java file –> Select Source –> Generate Constructor with Fields…

Step 3: Choose fields for which you want to include in Constructor parameter

Note:

  • it can be limited by un-checking fields whichever isn’t required
  • allows to indicate insertion point like after which field/method, generated constructor needs to be placed
  • also, we can specify Access Modifier; but generally it is selected as public unless we are going to generate constructor for Singleton
  • and there are few other things which comes handy while generating constructor for any Java class

Step 4: View Java file with all attributes inside 4-arg parameterized constructor

Here, it is!!

4. Useful Eclipse IDE shortcuts :

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Eclipse IDE - How to generate getters and setters ?
Eclipse IDE - How to comment and uncomment line & block ?