Can we define a static constructor in Java?

JavaObject Oriented ProgrammingProgramming

No, we cannot define a static constructor in Java, If we are trying to define a constructor with the static keyword a compile-time error will occur.

In general, static means class level. A constructor will be used to assign initial values for the instance variables. Both static and constructor are different and opposite to each other. We need to assign initial values for an instance variable we can use a constructor. We need to assign static variables we can use Static Blocks.

Example

Live Demo

public class StaticConstructorTest {
   int x = 10;
   // Declaratiopn of Static Constructor
   static StaticConstructorTest() {
      System.out.println("Static Constructor");
   }
   public static void main(String args[]) {
      StaticConstructorTest sct = new StaticConstructorTest();
   }
}

In the above example, we have created a static constructor. the code doesn't compile and it can throw an error says that modifier static not allowed here.

Output

StaticConstructorTest.java:4: error: modifier static not allowed here
raja
Published on 28-Jun-2019 18:24:58
Advertisements