In this article, we will discuss how to generate constructor with fields for a Java class
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)
IDE era:
- 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.
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!!
References:
- https://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fref-menu-source.htm
- https://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fref-dialog-gettersetter.htm
Happy Coding !!
Happy Learning !!