Static Constructor in Java

Have you ever heard Static constructor in Java, In Java constructor, can’t be Static?  If you try to declare the constructor static then the compiler will throw an error.

 

Why Constructor can’t be static ?

Static members belong to the class only like Static methods can’t be inherited. As we all are aware of the Constructor chaining concept. So we know that subclass calls the constructor of the super class, so if you mark the constructor 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 the reason why a constructor cannot be static. Let’s take an example and see how compiler will slap us-

Output :

Exception in thread “main” java.lang.Error: Unresolved compilation problem: 
    Illegal modifier for the constructor in type StaticParent; only public, protected & private are permitted

 

Automation Testing Video Tutorial:

0 Comment

Leave a Reply