|
You can apply the static modifier to methods. A static method is
associated with a class rather than the instances. For this reason, it
is sometimes called as a class method as
well.
Static methods are appropriate when the behavior they implement is associated with a class rather than the objects of that class. For example, if you have a class that has a common utility method, which does not do any instance-specific thing. If such method is written as instance method, you will need to create instance of such class just to use that method. To avoid this unnecessary instance-creation, the method is declared as static. For example, The Java standard library contains a String class in java.lang package that has declared several valueOf() methods as static. These utility methods simply return the string representation of the passed argument. This behavior is not really that of a string object but a generic behavior. Therefore, it is defined in static methods so that it can be used without creating any String instance. Static methods are usually defined to implement some utility functions or to manipulate the static member variables.
|
|
Java runtime system loads class whenever it is referred first time in the currently running code. When you refer the static variables or static method of a class, Java runtime checks whether the class in loaded. If not, it will load it. Thus, a Java class can be loaded even if no instance of it is created. |
Declaration facts for static method
Syntactically static methods look just like instance methods of a class except it uses the static keyword in the declaration. The real difference between the two is the way static methods are used. Following are the additional facts that emphasize the difference.
Static method can be called even before any instance of a class
is created. You can invoke them either by using the class name in which
it is defined or using an instance of that class.
A static method may never be declared as abstract.
A static method can access only static members of the
class. It does not have access to the non-static members. Therefore, an attempt
to reference the current object using the keyword this or the keyword super
in static method results in a compile-time error.