Java Constructor Creation with Example


Java Constructor plays an important role in code development. A constructor looks like a method but without any return type. Moreover, the name of the constructor and class name should be the same.

The advantage of constructor is it is called implicitly when an on object is created. That is, we write a constructor but we never call explicitly. It is automatically called (ofcourse, an object should be created). The same thing in case of methods, a method should be defined and called explicitly with an object.

Now let us see how to create a Java constructor.

public class Employee
{
  public Employee()                        // defining a constructor
  {
    System.out.println("OK 1");
  }
  public static void main(String args[])
  {
    Employee emp1 = new Employee();        // creating object to call the constructor
    Employee emp2 = new Employee();
    Employee emp3 = new Employee();
  }
}

Java Constructor

public Employee()

The above statement defines a Java constructor. Observe, the class name and constructor name are same. Just to know that constructor is called, a println() statement is given.

Employee emp1 = new Employee();
Employee emp2 = new Employee();
Employee emp3 = new Employee();

In the main() method, three objects emp1, emp2 and emp3 are created. Each object calls the constructor and prints OK 1. That is, three times the Java constructor is called and OK 1 is printed three times.

Employee emp1 = new Employee();

In the above statement, the last word Employee() denotes a constructor. It infers, to create an object, compulsorily constructor is to be called.

Note: Do not try to call a constructor like a method. emp1.Employee() raises compilation error.

Increase your Java Constructor Knowledge

Leave a Comment

Your email address will not be published.