Java: Static Constructor – A big interview question ?

In this article, we will learn and understand why Java doesn’t allow static constructor in detail

Static constructor:

There is no such thing known as Static constructor in Java. Then why it is important to discuss here

Before we move ahead and discuss “why Java doesn’t allow static constructor”, we will review and understand about “Java Constructor” first

Read more about Java Constructor here

 

Java Constructor

In simple words, constructor is a special type of method that is used to initialize an object and contains no return type. So, constructors are invoked at the time of instance creation and are more related to instance rather class

Whereas static related fields, blocks, methods or classes are loaded at the class load into JVM and thus belongs to class like

  • Static fields are class variables
  • Static methods are class methods
  • Static blocks i.e.; static initialization block
  • Static classes i.e.; top-level classes

Note: static are related to class rather to any specific object

 

Let us see a simple Java class with “static” keyword prefixed to default constructor in same class

TestStaticConstructor.java

Simple and straightforward Java class with default constructor with “static” keyword prefixed

1_Static_constructor_in_java_compile_time_error

Error:

Compile-time error: Illegal modifier for the constructor in type TestStaticConstructor only public, protected & private are permitted

Explanation:

From above example we can derive that,

  • Only access modifier like private, default, protected, public are allowed
  • Non-access modifiers like static, final, transient, volatile, strictfp, synchronized are not allowed

It is very much clear now that, only access modifier are allowed and non-access modifier like static are not allowed in the constructor signature

 

But very important question is why Java doesn’t allow to have static constructor?

As we discussed in earlier section, constructor are invoked every time we create a new instance and constructor will become inaccessible by marking constructor as static

Also there exists an implicit super() constructor call in every constructor and likewise programmer can also explicitly declare a this() constructor call or super() constructor call in constructor chaining process which should be 1st constructor statement, if present

So, in constructor chaining process it will be inaccessible at the time of object creation. For this reason, Java doesn’t support static constructor

 

Let us consider one simple example to understand it programmatically

ParentClass.java

Super class with default no-arg constructor and display method to print message

2_Static_constructor_in_java_parent_class

ChildClass.java

Child class with default no-arg constructor and display method to print message which inherits above super class ParentClass

main() method – execution start point or JVM entry point to begin execution

3_Static_constructor_in_java_child_class

Output:

ParentClass >> Super class constructor
ChildClass >> Sub class constructor
ChildClass >> displayMethod()invoked of sub class

 

Explanation:

In above inheritance example,

  • We have created simple super class called “ParentClass” & another sub class called “ChildClass” extending super class
  • Both classes got default no-arg constructor with simple print message to understand the execution flow
  • Sub class overrides display() method to print simple message
  • Now, when we created an object of type ChildClass inside main() method using “new” keyword
  • 1st super class constructor and then secondly sub class constructor gets executed
  • Finally display method is invoked to print the message using newly created object

In inheritance concept, super class constructor gets called either implicitly or explicitly by the programmer

So, it is important that constructor should be made non-static so that it is accessible for every object creation which initializes with initial values

By making constructor as static, it gets attached to class rather with every instances and isn’t accessible while object instantiation and thus not allowed in Java

 

But why we need such thing like “static constructor” which is never allowed in Java?

Basically to initialize static variables while class loading at class-level;

But it should be clear by now that there is nothing like static constructor in Java. Also, we have understood that static belongs to class rather to objects

A good alternative solution to this is having static {initialization block} anywhere in class body, which does static initialization at class-level

We will see in detail about static initialization in the upcoming article but before that, we will give a quick look through simple example demonstrating static blocks in Java class

 

Static blocks

Static {initialization block} alternatively known as static blocks or static initializers in Java

Note: static blocks are executed in the order they are declared in class and they are one time activity at the time of class load

 

StaticInitializationBlockExample.java

Sample class with two static block at 2 different places in class body, a default no-arg constructor and instance method which is invoked after object creation

package in.bench.resources.constructor.example;

public class StaticInitializationBlockExample {

	// static initialization block - 1
	static {
		System.out.println("StaticInitializationBlockExample >> static block - 1");
	}

	// default constructor
	StaticInitializationBlockExample() {
		System.out.println("StaticInitializationBlockExample >> default no-arg constructor");
	}

	// display() - instance method
	void display() {
		System.out.println("StaticInitializationBlockExample >> print message for display() method");
	}


	// static initialization block - 2
	static {
		System.out.println("StaticInitializationBlockExample >> static block - 2");
	}

	// main() method - entry point to JVM
	public static void main(String[] args) {
		StaticInitializationBlockExample sibe = new StaticInitializationBlockExample();
		sibe.display();
	}
}

Output:

StaticInitializationBlockExample >> static block - 1
StaticInitializationBlockExample >> static block - 2
StaticInitializationBlockExample >> default no-arg constructor
StaticInitializationBlockExample >> print message for display() method

Explanation:

In above example,

  • There are 2 static blocks, one is defined before default constructor and other is defined before main() method
  • They are executed first irrespective of the place they are defined that is even before default constructor invocation while creating object
  • Also, they are executed in the order they are defined
  • Executed only once

So, static initializers are good alternative and helpful to initialize static variables at class load itself i.e.; variables get memory allocation at the time of class load itself

 

References:

https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

 

Read Also:

Happy Coding !!
Happy Learning !!

Java: Constructor in Interface – A tricky question post Java 8 release
Java: Private Constructor