How and where to use Static modifier in Java?

You can think of a ‘static’ method or field as if it were declared outside the class definition. In other words

  1. There is only one ‘copy’ of a static field/method.
  2. Static fields/methods cannot access non-static fields/methods.

There are several instances where you would want to make something static.

The canonical example for a field is to make a static integer field which keeps a count across all instances (objects) of a class. Additionally, singleton objects, for example, also typically employ the static modifier.

Similarly, static methods can be used to perform ‘utility’ jobs for which all the required dependencies are passed in as parameters to the method – you cannot reference the ‘this’ keyword inside of a static method.

In C#, you can also have static classes which, as you might guess, contain only static members:

public static class MyContainer
{
    private static int _myStatic;

    public static void PrintMe(string someString)
    {
        Console.Out.WriteLine(someString);
        _myStatic++;
    }

    public static int PrintedInstances()
    {
        return _myStatic;
    }
}

Leave a Comment