Static means that their is no instance variable associated, and that you can access the members of a static class by using the class name itself. Because of this property of a static class, there is no “new” keyword usage.
Within the program there would actually only ever be a single instance of the class, it’s members or methods. Therefore, a static class is never instantiated. A static class also does not have an instance constructor and are sealed, meaning they cannot be inherited .
This means, if I have a static class Person with a member:
public static String name;
As soon as my program runs [name] is available to set its value. I can access and this static variable simply with:
Person. name = “Emily”;
Why use the static keyword?
According to Microsoft, “a static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields. ”
This is true, but as our program grow relying on static classes as containers for helper methods can become difficult to maintain. If we elect to use static class as this sort of container, which can only contain static members, it is important to thoughtfully design our program to avoid a hodgepodge of odds and ends we can’t mentally sort through.
Additionally, static variables let us create constants in our programs. These constants can be retrieved by invoking the class without creating an instance of it. This is very convenient when we want to ensure that only one copy of the variable will ever be created. The compiler will enforce this rule for us. An example I use a lot is a log file directory. I can have a single instance of the directory path: c:\blah\blah\20190604_errorlog.txt and pass ensure that even when my logging class is called this variable containing the path persists throughout.
The static keyword lets us quickly create a persistent class, member or method that we can access without creating a new instance. We can invoke the class directly without creating additional instances.
A Web Developer by trade, future data scientist.
A motorcycle enthusiast at heart.
Most days I’d rather be in the woods anywhere.