Static methods are declared in a class and belong to the class, not an object. They are used in utility classes and cannot access instance variables. Inheritance with static methods can cause issues with polymorphism.
An object-oriented computer programming method that is declared in a class but does not depend on any particular instance of that class is called a static method. Most programming languages include the static keyword in a method declaration to make a method static. These methods belong strictly to the class in which they are contained and not to any object instantiated by that class. They are often referred to as class methods.
The literal class name is normally used to access a static method instead of referring to it by 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 don’t depend on instance variables of a particular class. They are also used when a programmer needs access to the method but does not need to instantiate the class in which it is contained. Utility classes are not normally instantiated in objects. It would be unusual for a utility method to need to change object information. A method of 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 static methods, instance methods are the type of methods normally used in regular classes.
One major disadvantage of static methods occurs during inheritance when polymorphism is used. Until the parent static method is declared final, the same child static method can be coded into the child class as if it had been 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 static child 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 static child method will use the parent method instead of the expected child method. With true polymorphism, the child method would be the one fired after an upcast.
Protect your devices with Threat Protection by NordVPN