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:
Consider the following points from Java Language Specification:
- Constructors, static initializers, and instance initializers are not members and therefore are not inherited.
- If a class declares a
static
methodm
, then the declarationm
is said to hide any methodm'
, where the signature ofm
is a subsignature of the signature ofm'
, in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class.
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:
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:
Post a Comment