Class or static Members

A method or a field in a Java program can be declared static. This means the member belongs to the class rather than to an individual object.

If a variable is static, then when any object in the class changes the value of the variable, that value changes for all objects in the class.

For example, suppose the Car class contained a speedLimit field that was set to 112 kph (70 mph). This would be the same for all cars. If it changed (by act of Congress) for one car, it would have to change for all cars. This is a typical static field.

Methods are often static is if they neither access nor modify any of the instance (non-static) fields of a class and they do not invoke any non-static methods in the class. This is common in calculation methods like a square root method that merely operate on their arguments and return a value. One way of thinking of it is that a method should be static if it neither uses nor needs to use this.

Previous | Next | Top | Cafe au Lait

Copyright 1997-1999 Elliotte Rusty Harold
Last Modified October 11, 1999