Is it possible to create static constructor in java?



A constructor is used to initialize an object when it is created. It is syntactically similar to a method. The difference is that the constructors have same name as their class and, have no return type.

There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation.

Static constructors

No, we cannot create a Static constructor in java You can use the access specifiers public, protected & private with constructors.

If we try to use static before a constructor a compile time error will be generated saying “modifier static not allowed here”.

Example

In the following Java example, we are trying to create a static constructor.

 Live Demo

public class Student {
   public String name;
   public int age;
   public static Student(){
      System.out.println("Constructor of the Student class");
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      new Student().display();
   }
}

Compilation error

On compiling the above program generates the following error −

Student.java:6: error: modifier static not allowed here
   public static Student(){
                ^
1 error

Advertisements