Java Constructor Creation with Example

May 4, 2014 | Constructors
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

  1. Java Constructor Properties
  2. Can Java constructor be final?
  3. Constructors and Constructor overloading
  4. Java Constructor Overriding
  5. Abstract class constructor & Interface abstract
  6. Java Passing Arrays to Constructor
  7. Static Constructor
  8. Private Constructor
  9. Protected Constructor
  10. Java this(): Calling Constructor from Constructor same class
  11. Java super(): Calling superclass constructor from subclass
  12. What Java constructor return?
  13. Java Constructors: Learn through Questions and Answers