You are here

Static fields and methods

15 January, 2016 - 09:02
Available under Creative Commons-ShareAlike 4.0 International License. Download for free at http://cnx.org/contents/402b20ad-c01f-45f1-9743-05eadb1f710e@37.6

Static fields and methods, denoted by the static keyword in their declarations, are fields and methods that can be accessed at a class level, not just an object level. In general these are values or behaviors that one wishes for all instances of a class to have access to. These values and behaviors are necessarily independent of the state of any particular instance. Static fields and methods are often referred to as "class variables" and "class methods".

An examples of a class variables are Math.PI and Color.BLUE or Color.RED. These are universal values associated with math and color respectively and thus do not need an object instance to be viable. By convention, all static field names are in all capital letters. A static field is referenced simply by writing the class name followed by a period and then by the field name. No instantiations are necessary.

The Randomizer class contains numerous static methods. This is because each of the methods to produce various random values is independent of each other and that the process in each method does not affect nor is affected by the state of the rest of the class. Essentially, this entails that the class contain no non-static fields. A class as such is referred to as being "stateless". Just like a static field, a static method is invoked in the same manner as the static fields: ClassName.staticMethodName(...) Classes with static methods are usually utility classes that are used to hold a set of related functional processes, e.g. Randomizer holds a collection of random value generators. Likewise, Math holds a combination of static values, such as PI and static methods such as sin() and cos().

There is one very special static method with the following exact signature:

public static void main(String[] args) 

This method, found in BallControl, is the method that Java uses to start programs up. Since OO programs are systems of interacting objects, this static "main" method is used to create the first object(s) and get the program up and running. So when Java starts a program, it looks for this and only this method.