Java Concepts‎ > ‎

Static methods

Static fields and methods belong to the class; therefore, they do not belong to any of instances of the class.

The instances of the class (objects) do not even have to exist for static methods to operate on the static fields. In fact, static methods cannot even access instance methods or variables within a class. A static method can use only local variables, static constants, and other static methods in the same class.

To call the static method we need to call the class containing the method, for example:
Class.method();

Static fields should be used in cases when a value cannot be stored in an instance field.
Note: For example, to keep a count of instances of a class created, we cannot increment a field which is located in an instance.

Static methods should be used in cases when it is impractical to use a method in an instance of a class.
Note: Some arithmetic computations (for example, adding two parameters) do not require the creation of a new object.

Static methods should also be used when we need an access to a method from many different classes. In this case, it is impractical to insert a new copy of the method into every class or instantiate a new object every time we need the method.
Note: For example, we can call a static JOptionPane.showMessageDialog() method from any class.
Comments