What is a Static Method?
An object orientated computer programming method that is declared in a class but is not dependent on any particular instantiation of that class is called a static method. Most programming languages include the keyword static in the declaration of a method to make a method static. These methods belong strictly to the class they are contained in and not to any object instantiated from that class. They are frequently referred to as class methods.
The literal name of the class is normally used to access a static method instead of referring to it with the name of an instantiated object. It is permissible in Java to use object names to refer to these methods, but it is strongly discouraged. If an object name is used, a person reading the code may confuse one of these methods with an instance method.
Static methods are often used in utility classes that do not depend on instance variables from any particular class. They are also used when a programmer needs to access the method but there is no need to instantiate the class it is contained in. Utility classes are normally not instantiated into objects. It would be unusual for a utility method to have a need to modify object information. A method from the java.lang.math class, such as pow(), would be an example of how this type of method would be used in a utility class.
Instance methods can directly access instance variables, static variables, instance methods, and static methods. Static methods cannot directly access instance variables and instance methods. Due to the nature of instance methods having better access to class members than a static methods, instance methods are the type of methods normally used in regular classes.
One major drawback of static methods occurs during inheritance when polymorphism is used. As long as the parent static method is not declared final, the same child static method can be coded in the child class as if it were being overridden. This is technically called hiding instead of overriding because a static method cannot be overridden.
When hiding is used, if the parent static method is accessed using the class name, the parent method will be used. If the overridden child static method is accessed using the object name, the overridden child method will be used. The problem occurs when a child object is upcast as a parent. In this case, a call to the upcast child static method will use the parent method instead of the expected child method. With true polymorphism, the child method would be the one activated after an upcast.
Discuss this Article
Post your comments