- Computers & Software
Introduction to Static Classes in Java
The static class plays an important part in Object Oriented Programming (OOP). This tutorial introduces basic concepts of static classes in the Java programming language.
Figure 01 illustrates how to create a basic static class. Simply put the keyword static in the declaration of the methods in the class. The declaration of the class itself requires no special decoration. The class can contain static and non-static methods and properties simultaneously.
Figure 02 contains a main() that references the static class. Note that the reference uses the class name, not an object (instance) name. An instance is not required.
An instance can reference a static member, but be sure to have a thorough understanding of the side effects.
Let's modify the static class. In Figure 03, the class has a new property, alpha, and a new method, SetAlpha(). SetAlpha() is public and alpha is private.
The SetAlpha() method references the private property alpha.
Note that alpha and SetAlpha() are not declared as static.
All is well in the main(); it still builds and executes properly. No changes are necessary.
In Figure 05 the main() is broken because it's illegal to reference a non-static method using a class reference. The converse is permissible, but that's not the point of this exercise..
OK, let's try to fix the error by declaring the SetAlpha( ) method static. Figure 05 illustrates the attempt.
That fails. The SetAlpha( ) method cannot be declared static because it references a non-static variable, alpha.
Figure 06 illustrates the only way to fix the problem. The declaration of alpha must be modified to include the keyword static.
However, although the project now builds properly, we have created a situation in which only one instance of the variable alpha will be created when the program runs.
Static classes are commonly used to create classes that do not need to be instantiated and will be shared as a single copy throughout the entire project.
The static class is also a first step in creating a design pattern called a Singleton.