Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll learn how Java deals with constructors and review some rules related to them from the Java Language Specification.

2. Constructor Declarations

In Java, every class must have a constructor. Its structure looks similar to a method, but it has different purposes.

Let’s see the specification of the constructor:

<Constructor Modifiers> <Constructor Declarator> [Throws Clause] <Constructor Body>

Let’s look at each piece separately.

2.1. Constructor Modifiers

Constructor declarations begin with access modifiers: They can be public, private, protected, or package access, based on other access modifiers.

To prevent compilation errors, constructor declarations may not have more than one private, protected, or public access modifier.

Unlike methods, a constructor can’t be abstract, static, final, native, or synchronized:

  • It isn’t necessary to declare a constructor final because they are not class members and they do not inherit.
  • The abstraction is unnecessary because we must implement the constructors.
  • A static constructor is not required since each constructor is called with an object.
  • An object under construction should not be synchronized since it would lock the object while it is being constructed, which is not normally made available to other threads until all the constructors have completed their work.
  • There are no native constructors in Java because this is a language design decision that is meant to make sure that superclass constructors are always invoked during object creation.

2.2. Constructor Declarator

Let’s examine the syntax of a Constructor Declarator:

Constrcutor Name (Parameter List)

There must be a match between the constructor name in the declarator and the name of the class that contains the constructor declaration, or else a compile-time error will occur.

2.3. Throws Clause

The structure and behavior of throws clauses for methods and constructors are both the same.

2.4. Constructor Body

The syntax of a constructor body is:

Constructor Body: { [Explicit Constructor Invocation] [Block Statements] }

We can explicitly call another constructor of the same class or a direct superclass as the first command in a constructor body. The direct or indirect invocation of the same constructor is not allowed.

3. Explicit Constructor Invocations

We can divide the invocations of constructors into two types:

  • Alternate constructor invocations begin with the keyword this. They are used to invoke alternate constructors of the same class.
  • Superclass constructor invocations begin with the keyword super.

Let’s look at an example of how we can use this and super keywords to invoke another constructor:

class Person {
    String name;

    public Person() {
        this("Arash");   //ExplicitConstructorInvocation
    }

    public Person(String name){
        this.name = name;
    }
}

Here, the first constructor of Employee invokes the constructor of its superclass Person, passing along the id:

class Person {
    int id;
    public Person(int id) {
        this.id = id;
    }
}

class Employee extends Person {
    String name;
    public Employee(int id) {
        super(id);
    }
    public Employee(int id, String name) {
        super(id);
        this.name = name;
    }
}

4. Rules of Constructor Invocation

4.1. this or super Must Be the First Statement in the Constructor

Whenever we call a constructor, it must call the constructor of its base class. In addition, you can call another constructor within the class. Java enforces this rule by making the first call in a constructor be to this or super.

Let’s take a look at an example:

class Person {
    Person() {
        //
    }
}
class Employee extends Person {
    Employee() {
        // 
    }
}

Here’s an example of constructor compilation:

.class Employee
.super Person
; A constructor taking no arguments
.method <init>()V
aload_0
invokespecial Person/<init>()V
return
.end method

Constructor compilation is similar to compiling any other method except that the generated method has the name <init>. One of the requirements for verifying an <init> method is that the call to the superclass constructor (or to some other constructor in the current class) must be the first step in the method.

As we can see above, the Person class must call its superclass constructor, and so on up to java.lang.Object.

When classes must call their superclass constructor, it ensures that they will never be used without proper initialization. The JVM’s security depends on this, as some methods will not work until the class has been initialized.

4.2. Don’t Use Both this and super in the Constructor

Imagine if we could use this and super together in the constructor body.

Let’s see what would happen through an example:

class Person {
    String name;
    public Person() {
        this("Arash");
    }

    public Person(String name) {
        this.name = name;
    }
}

class Employee extends Person {
    int id;
    public Employee() {
        super();
    }

    public Employee(String name) {
        super(name);
    }

    public Employee(int id) {
        this();
        super("John"); // syntax error
        this.id = id;
    }

    public static void main(String[] args) {
        new Employee(100);
    }
}

We cannot execute the above code because a compile-time error will appear. The Java compiler has its logical explanation, of course.

Let’s take a look at the constructor invocation sequence:

constructor-2

The Java compiler does not permit compilation of this program because initialization is unclear.

4.3. Recursive Constructor Invocation

The compiler will throw an error if a constructor calls itself. For example, in the following Java code, the compiler will throw an error because we’re trying to call the same constructor within the constructor:

public class RecursiveConstructorInvocation {
    public RecursiveConstructorInvocation() {
        this();
    }
}

Despite the Java compiler’s restriction, we can compile the program by changing the code slightly, but we will encounter a stack overflow this way:

public class RecursiveConstructorInvocation {
    public RecursiveConstructorInvocation() {
        RecursiveConstructorInvocation rci = new RecursiveConstructorInvocation();
    }

    public static void main(String[] args) {
        new RecursiveConstructorInvocation();
    }
}

We’ve created a RecursiveConstructorInvocation object that is initialized by calling the constructor. The constructor then creates another RecursiveConstructorInvocation object that is initialized by calling the constructor again until the stack overflows.

Now, let’s see the output:

Exception in thread "main" java.lang.StackOverflowError
	at org.example.RecursiveConstructorInvocation.<init>(RecursiveConstructorInvocation.java:29)
	at org.example.RecursiveConstructorInvocation.<init>(RecursiveConstructorInvocation.java:29)
	at org.example.RecursiveConstructorInvocation.<init>(RecursiveConstructorInvocation.java:29)
//...

5. Conclusion

In this tutorial, we discussed the specification of constructors in Java and reviewed some rules for understanding the invocation of constructors in a class and superclass.

As always, code samples can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.