Constructor in Java

A constructor in Java is a special type of method that is automatically called when an object is created from a class. The purpose of a constructor is to initialize the object’s state by setting its initial values. A constructor has the same name as the class and does not have a return type, not even void.

Constructors allow us to initialize objects with specific values, avoiding the need to set values manually after object creation. This can save us a lot of time and make our code more readable and maintainable.

Types of constructors in Java

There are two different types of constructors that we can use in Java, these are:

  • Default constructors: Constructors that have no parameters create a default instance of the class. If we don’t provide any constructors in our class, the Java compiler will automatically create a default constructor for us.
  • Parameterized constructors: These are constructors that accept one or more parameters and use them to initialize the object’s instance variables. We can create as many parameterized constructors as we like, as long as each one has a unique set of parameters.

It’s important to note that constructors do not have a return type, not even void. This is because the purpose of a constructor is to create and initialize an object, not to return a value.

Constructor example

Following is an example of a simple class that has a default constructor and a parameterized constructor:

public class Employee {
   private String name;
   private int age;
   private double salary;
   
   // Default constructor
   public Employee() {
      this.name = "";
      this.age = 0;
      this.salary = 0.0;
   }
   
   // Parameterized constructor
   public Employee(String name, int age, double salary) {
      this.name = name;
      this.age = age;
      this.salary = salary;
   }
   
   // Getters and setters for instance variables
   public String getName() {
      return this.name;
   }
   
   public void setName(String name) {
      this.name = name;
   }
   
   public int getAge() {
      return this.age;
   }
   
   public void setAge(int age) {
      this.age = age;
   }
   
   public double getSalary() {
      return this.salary;
   }
   
   public void setSalary(double salary) {
      this.salary = salary;
   }
}

To use these constructors, we can create new instances of the Employee class like this:

// Use default constructor to create an employee with default values
Employee employee1 = new Employee();

// Use parameterized constructor to create an employee with specific values
Employee employee2 = new Employee("John Smith", 30, 50000.0);

Constructors are a powerful feature of the Java programming language. They allow us to create objects that are properly initialized and ready to use. Whether we’re using default constructors or parameterized constructors, they provide a simple and effective way to create objects that are ready to use. However, it’s important to remember that constructors are not the only way to initialize objects in Java. We can also use instance initialization blocks and initialization methods to set the initial values of our objects.

Block initialization

Instance initialization blocks are blocks of code that are executed when an object is created before the constructor is called. They are defined within the class, but outside of any method or constructor. We can use instance initialization blocks to set the initial values of instance variables or to perform any other tasks that need to be done before the object is fully initialized.

Syntax:

{
    // code for initializing instance variables
}

Example of instance block initialization

public class Rectangle {
    private int length;
    private int width;

    {
        length = 10;
        width = 5;
    }

    public Rectangle() {
        // Default constructor
    }

    public Rectangle(int length, int width) {
        // Parameterized constructor
        this.length = length;
        this.width = width;
    }

    // Getter and setter methods
    ...
}

In the above example, we have declared an instance block outside of any method or constructor. It sets the default values for the length and width variables to 10 and 5, respectively. The Rectangle class also has two constructors: a default constructor and a parameterized constructor. The default constructor does not set the values of length and width, so they will be set to the values defined in the instance block. The parameterized constructor takes two arguments: length and width, and sets the values of the instance variables accordingly.

Initialization method

Initialization methods are methods that are specifically designed to initialize an object. They can be called from the constructor or from any other method in the class. Initialization methods are useful if we want to provide a convenient way to set the initial values of an object, or if we need to perform a complex initialization process that cannot be easily done in a constructor.

Syntax:

public void initMethod() {
    // code for initializing instance variables
}

Here is an example of how to use IIBs and an initialization method to set the initial values of an object:

class Example {
    int x;
    int y;
    {
        x = 1;
    }
    public Example() {
        y = 2;
    }
    public void initMethod() {
        x = 3;
        y = 4;
    }
}

In the example above, the instance variable x is initialized to 1 in the instance initialized block, and the instance variable y is initialized to 2 in the constructor. The initMethod() can be called later in the code to re-initialize the x and y to 3 and 4 respectively.

Conclusion

Constructors, instance initialization blocks, and initialization methods are all useful tools for creating and initializing objects in Java. Whether we need to create a default object with default values, a fully customized object with specific values, or an object that requires a complex initialization process, we have a variety of options to choose from. By understanding the different ways to initialize objects in Java, we can write more efficient and maintainable code for our projects.

Leave a Reply

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x