
Static Method
The static keyword can also be applied to a method. A static method, like a static variable, is associated with
the class, not the objects (instances). Static methods are also called class methods (versus nonstatic methods,
which are instance methods). Methods you have seen so far are instance methods. Below, another instance
method, drive(), is added to the Car class.
public class Car{
String color;
String type;
void drive() {
System.out.println(“Put ‘er in gear and drive it like you stole it”);
}
...
}
To call an instance (nonstatic) method, you must have an object reference.
Car c = new Car();
c.drive(); //Correct
Car.drive(); //Wrong (what car are you driving?)
To define a static method, simply add the static keyword as a modifier to the method as shown below.
public class Car{
...
static void resetCarCount(){
carCount = 0;
}
...
}
To call a static method, you only need the name of the class.
Car c = new Car();
c.resetCarCount(); //Legal but confusing
Car.resetCarCount(); //Proper way to code
As shown above, just as with class variables, you can call on a static method using any object of that type.
However, this makes it look like resetCarCount() is an instance method, doesn’t it? Again, it is considered
clearer, and preferred, to use the class name when accessing static methods.
Static methods do not have access to object data. Looking at the example below, what color are you changing
if you called resetCarCount?
public class Car{
...
static void resetCarCount(){
carCount = 0;
color = “blue”; //Wrong - which instance’s color are you changing?
}
...
}
Now you might be asking yourself, “What’s the point of static methods?” If so, that’s a good and fair
question. Static methods essentially have two purposes.
1) They are used to access (update or fetch) class variable data. Although this can be done with any
instance of the class, it is considered more appropriate to use class methods for this purpose. In
some cases, you may not have an instance of an object created before the data is needed. You
don’t want to have to create an object just to be able to access class variables.
2) Static methods provide functionality without the need for an object/instance. For example,
mathematical formulas are great reasons to have static methods. Should you have to create an
instance of some object to compute sine, cosine, or tangent? Examine the Math class to see some
excellent uses of static methods. There is no need to create an instance of Math to compute the
absolute value of a number!
Static Methods
Table of Contents
Copyright (c) 2008. Intertech, Inc. All Rights Reserved. This information is to be used exclusively as an
online learning aid. Any attempts to copy, reproduce, or use for training is strictly prohibited.
Courseware
Training Resources
Tutorials
Services