Java Constructor Example: Default and Parameterized

Java constructors are special method-like constructs that allow fully initializing the object state before other classes inside the application can use it. Constructors are invoked using new keyword.

1. What is a Constructor in Java?

Constructors are special method-like (but not exactly methods) constructs that help programmers write object initialization code, before the object is available for use by other objects in the application.

public class MyClass {

  public MyClass() {
    //...
  }
}

Whenever an application needs a new instance of any class, JVM allocates a memory area inside the heap. Then JVM executes the invoked constructor (the class can have multiple constructors) and initializes the object state. Inside the constructor, we can access all object attributes and assign them to their default or desired values.

If we do not define any constructor in a class, JVM automatically inserts a default constructor with an empty body.

2. Rules to Create Constructors in Java

There are a few mandatory rules for creating the constructors in Java.

  • The constructor name MUST be the same as the name of the class.
  • There cannot be any return type in the constructor definition.
  • There cannot be any return statement in the constructor.
  • Constructors can be overloaded by different arguments.
  • If you want to use super() i.e. parent class constructor, then it must be the first statement inside the constructor.

3. Default and Parameterized Constructors

The constructors can be of two types. One that accepts no argument is also called the default constructor. Other constructors that accept arguments are called parameterized constructors.

Java constructor

3.1. Default Constructor

If we do not provide any constructor in the class, JVM provides a default constructor to the class during compile time. In the default constructor, the name of the constructor MUST match the class name, and it should not have any parameters.

public class Employee { 

  public Employee() {
     super();
  }
}

Note that we also can override the default constructor and add more code related to state initialization.

public class Employee { 

  public Employee() {

     //addtional statements
     this.age = calculateAgeFromDateOfBirth();
  }
}

3.2. Parameterized Constructor

There can be multiple constructors in a class. We can define overloaded constructors in class that accepts a different set of parameters in each constructor.

public class Employee {

  private String firstName;
  private String lastName;
 
  public Employee() { //constructor 1

  }
 
  public Employee(String firstName) { //constructor 2
       //statements
  }
 
  public Employee(String firstName, String lastName) { //constructor 3
       //statements
  }
}

If we define a non-default parameterized constructor in a class then JVM will not insert the default constructor in the bytecode. In such case, if default constructor is required, we must create the default constructor explicitely.

For example, in the following Employee class, we have created only one parameterized constructor:

class Employee {

  public Employee(String name) {
  }

}

If we try to create an instance of Employee using the default constructor, then a compilation error will occur:

Employee employee = new Employee();  //'Employee(java.lang.String)' in 'Employee' cannot be applied to '()'

4. Constructor Chaining with this() and super()

In Java, it is possible to call other constructors inside a constructor. It is just like method calling but without any reference variable (obviously, as the instance is NOT fully initialized as of now).

Now we can call constructors of either the same class or of the parent class. Both use different syntaxes.

4.1. Calling Same Class’s Constructors with this()

To call other constructors from the same class, use this keyword. In the following code, this() invokes the default constructor, and this(firstName) invokes the first constructor accepting a single argument of type String.

public Employee() {	
}

public Employee(String firstName) {
	this();		//calling default constructor
}

public Employee(String firstName, String lastName) {
	this(firstName);	//calling constructor with single argument of String type
}

4.2. Calling Parent Class’s Constructors with super()

To call constructors from super or parent class, use super keyword. The usage of super keyword is similar to this keyword – the only difference is that super refers to superclass and this refers to the current instance.

public class Parent {

  public Parent() {
    //...
  }
}

public class Child extends Parent {

  public Child() {
    super(); //invokes Parent's constructor
  }
}

5. Private Constructors

Sometimes we want to protect the constructor from being called by other classes. Altogether we want that nobody should be able to create a new instance of the class.

Why would anybody want that? Well, it’s necessary for singleton pattern. In singleton, an application wants to have one and only one instance of any class.

A common singleton class definition looks like this:

public class DemoSingleton implements Serializable
{
    private static final long serialVersionUID = 1L;

    private DemoSingleton() {
        // private constructor
    }

    private static class DemoSingletonHolder {
        public static final DemoSingleton INSTANCE = new DemoSingleton();
    }

    public static DemoSingleton getInstance() {
        return DemoSingletonHolder.INSTANCE;
    }

    protected Object readResolve() {
        return getInstance();
    }
}

That’s all about constructors in java. Drop me your questions in the comments section.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode