Way2Java

Can you make Static Constructor in Java?

Java does not permit to declare a constructor as static. Following are the reasons.

1. Static means for the same class. For example, static methods cannot be inherited.

2. With static, "this" reference (keyword) cannot be used. "this" is always linked to an object. A constructor always belongs to some object.

3. If a constructor is static, an object of subclass cannot access. If static is allowed with constructor, it is accessible within the class but not by subclass.

The following program raises compilation error.

public class Demo
{
  public static Demo()
  {
    System.out.println("Hello 1");
  }
  public static void main(String args[])
  {
    Demo d1 = new Demo();
  }
}



Output screen on Static Constructor

Observe, the compiler error message. It says, static is not allowed with constructor.

What other access modifiers a constructor cannot be?

"A constructor cannot be abstract, static, final, native, strictfp, or synchronized". Explained clearly in Java Constructor Properties

Pass your comments and suggestions on this tutorial "Static Constructor".

Are you thorough with arrays? Then read this: Converting Numbers to Words

  1. Clear your confusion on Constructors: Java Constructors: Learn through Questions and Answers
  2. Can you convert in between Binary and Octal: int to Binary, Octal, Hexa