Java Static Constructor is not allowed, but why? Before we dig into the reasons for not allowing static constructor, let’s see what happens if we want to make a constructor static.

Java Static Constructor

Let’s say we have a class defined as:

If you will try to compile this class, you will get an error message as Illegal modifier for the constructor in type Data; only public, protected & private are permitted.

java-static-constructor

Why Static Constructor is not allowed?

Let’s see some of the reasons that make the compelling arguments for not allowing static constructor in java.

Static Belongs to Class, Constructor to Object

We know that static methods, block or variables belong to the class. Whereas a Constructor belongs to the object and called when we use the new operator to create an instance. Since a constructor is not class property, it makes sense that it’s not allowed to be static.

Static Block/Method can’t access non-static variables

We know that static methods can’t access non-static variables. Same is true for static block also.

Now, the main purpose of a constructor is to initialize the object variables. So if we make constructor as static then it won’t be able to initialize the object variables. That will defeat the whole purpose of having a constructor for creating the object. So it is justified to have the constructor as non-static.

Notice that we can’t use this inside a static method to refer to the object variable. Below code will give compilation error as: Cannot use this in a static context.

Static Constructor will break inheritance

In Java, every class implicitly extends Object class. We can define a class hierarchy where subclass constructor calls the superclass constructor. This is done by super() method call. Most of the times JVM automatically calls the superclass constructor but sometimes we have to manually call them if there are multiple constructors in the superclass.

Let’s see an example for super() usage.

Above program will produce the following output.

If you look at the super() method, it’s not static. So if the constructor becomes static, we won’t be able to use it and that will break inheritance in java.

Java Static Constructor Alternative

If you want to initialize some static variables in the class, you can use static block. Note that we can’t pass arguments to the static block, so if you want to initialize static variables then you can do that in the normal constructor too.

Summary

Java static constructor is not allowed and we have very good reasons for that. We can initialize static variables using the static block as well as through constructor itself.

By admin

Leave a Reply

%d bloggers like this: