Can We Make Constructor Static in Java?

Constructor cannot be marked as static in Java because static context belongs to the class, not the object. Therefore, onstructors are invoked only when an object is created, there is no sense to make the constructors static.

For experiment, if you try declaring a constructor static you will get compile-time error.

In some situations we use static blocks as an alternative. Java has static blocks which can be treated as static constructor. Following piece of code demonstrates that.

public class StaticDemo{
    static{
        System.out.println("static block of parent class");
    }
}
public class StaticDemoChild extends StaticDemo{
    static{
        System.out.println("static block of child class");
    }
    public void display()
    {
        System.out.println("Just a method of child class");
    }
    public static void main(String args[])
    {
        StaticDemoChild obj = new StaticDemoChild();
        obj.display();
    }
}
 
Output:
static block of parent class
static block of child class
Just a method of child class

In above mentioned example we have used static blocks in both the classes which worked perfectly. We cannot use static constructor so it is a good alternative if we want to perform a static piece of work during object creation.

Hope until this point you got the idea that why can't we have a constructor to be static in Java?. Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.