BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java static constructor – Is it really Possible to have them in Java?

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

Have you heard of static constructor in Java? I guess yes but the fact is that they are not allowed in Java. A constructor can not be marked as static in Java.  Before I explain the reason let’s have a look at the following piece of code:

public class StaticTest
{
     /* See below - I have marked the constructor as static */
     public static StaticTest()
     {
         System.out.println("Static Constructor of the class");
     }
     public static void main(String args[])
     {
         /*Below: I'm trying to create an object of the class
          *that should invoke the constructor
          */
         StaticTest obj = new StaticTest();
     }
}

Output: You would get the following error message when you try to run the above java code.
“modifier static not allowed here”

Why java doesn’t support static constructor?

It’s actually pretty simple to understand – Everything that is marked static belongs to the class only, for example static method cannot be inherited in the sub class because they belong to the class in which they have been declared. Refer static keyword.
Lets back to the point, since each constructor is being called by its subclass during creation of the object of its subclass, so if you mark constructor as static the subclass will not be able to access the constructor of its parent class because it is marked static and thus belong to the class only. This will violate the whole purpose of inheritance concept and that is reason why a constructor cannot be static.

Let’s understand this with the help of an example –