Saturday, April 27, 2019

Can we have static constructor in java?

Problem statement:
Can we have static constructor in java?

No ! we cannot have static constructor in java. The purpose of constructor is to initialise the object of the class. So there is no meaning to make constructor as static and thus compiler gives an error at compile time saying modifier 'static' not allowed.
  1. public class NoStaticConstructor {
  2.     public static NoStaticConstructor() {
  3.         System.out.println("default");
  4.     }

  5.     public static void main(String[] args) {
  6.         NoStaticConstructor st = new NoStaticConstructor();
  7.     }
  8. }
Output: compile time error - modifier 'static' is not allowed

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...