Saturday, January 11, 2014

Why can a constructor not be marked static in Java?

Constructors are called automatically at the time of creation of the instance of the class. A constructor is meant to set instance variables and it could not access them if it were static. So this question itself does not make sense. But, lets continue this for sake of curiosity.

Consider the following points from Java Language Specification:

  1. Constructors, static initializers, and instance initializers are not members and therefore are not inherited.
  2. If a class declares a static method m, then the declaration m is said to hide any method m', where the signature of m is a subsignature of the signature of m', in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class. 
But we have static initialization blocks which can be viewed as "static constructor":
class Foo {
  static String Bar;
  static {
     // "static constructor"
     Bar = "Hello world!";
Actually the only method in main class that must be static is main() method, because it is invoked without creating first instance of the main class. The following are worth reading:
  1. Classes and Objects
  2. Understanding Instance and Class Members
One point to notice is: static methods are sometimes more handy than a constructor. When we have an object of immutable type (for example String) then using a constructor will always create a new object, whereas by using static methods we can reuse the same object (rather it it recommended). We can also reuse mutable objects when we know they will not be altered in anyway.

No comments: