In this example ,we illustrate how Eclipse provides several possibilities to generate code.Code generation save significant time during development. For example Eclipse can override methods from superclasses and generate the toString(), hashcode() and equals() methods. It can also generate getter and setter methods for attributes of your Java class.

To generate code, select these options in the Source menu.

How to generate code in eclipse?-code.jpg
Figure: To select the code generation


We provide an example to test the code generation. We first create the following class in the project

Java Code: Creating a class
package myproject.first;

public class Person {
  private String firstName;
  private String lastName;

}
Then Select Source → Generate Constructor from Fields, mark both fields and press the OK button.

How to generate code in eclipse?-code-2.jpg
Figure: Generating constructor using Fields


Select Source → Generate Getter and Setter, select again both of the fields and then the OK button.
Select Source → Generate toString(), mark again both fields and press the OK button.

This will create following class:

Java Code: Java Source Code generated from a class
package myproject.first;

public class Person {

    private String firstName;
    private String lastName;

    public Person(String firstName, String lastName) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "Person [firstName=" + firstName + ", lastName=" + lastName
                + "]";
    }
}