Site icon TestingDocs.com

Generate Constructors in Eclipse IDE

Introduction

Let’s learn the steps to generate constructors for a class using the IDE tool in this tutorial. Constructors are called automatically when a new object is created for the class. In Java, we use the keyword new. Constructors always have the same name as the class. Constructors do not return or don’t have a return type.

Product class

Let’s create a class Product with three fields: name, price, and quantity.

To create a class in Eclipse IDE.

Launch Eclipse IDE.

File >> New >> Class

 

 

Enter the class name and click on the Finish button.

Enter private fields for the class. For example,

private String name;
private double price;
private int quantity;

Note the different data types we have used for the variables.

Generate Constructor

Now, we can use Eclipse to generate constructors for the class automatically, without writing any piece of code.

Right-click in the Java Editor >> Choose the Source >> Generate Constructor using fields…

 

 

In the resulting dialog, choose the fields and the insertion point. Optionally, you may generate comments for the constructor.

Click on the OK button, to create the constructor for the class.

It’s a best practice to generate comments for the methods. They make your code more readable and add it to the documentation.

Code

public class Product {
private String name;
private double price;
private int quantity;


/**
* @param name
* @param price
* @param quantity
*/
public Product(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}

}

 

Instantiating the Product class sample:

Product p = new Product(“Fan”,9.00,50);

// Product named Fan, price 9$ and quantity 50 units

Look how Eclipse helped to generate constructor code for you. Automatic code generation is one of the several benefits of using an IDE like Eclipse or IntelliJ would help you to develop code quickly.

Eclipse IDE Tutorials

Eclipse Tutorials on this website can be found at:
https://www.testingdocs.com/eclipse-tutorials

For more details on the Eclipse IDE, visit the official website at:
https://www.eclipse.org

Exit mobile version