TOPIC 1.10 · STUDY
Calling Class Methods
A class method is static: it belongs to the class, not to one constructed object. From another class, call it as ClassName.method(arguments). Inside the same class, you may omit the class name when the method is accessible.
1.10.A
Calling class methods
A class method is declared static. It belongs to the class itself. You do not need a constructed object of that class before you call it, and the call is not aimed at one particular instance.
From a different class, the usual form is ClassName.method(arguments). The class name comes first, then a dot, then the method name and parentheses. For a method watts in class RadioTower with no arguments, that call is RadioTower.watts().
int signal = RadioTower.watts();
System.out.println(signal);
That line asks the RadioTower class for watts. It does not create a RadioTower object, and it does not pick one tower among several. The result, if any, can be stored or printed like any other value.
The solid path targets the class. The faded path is the wrong idea: a class method call is not routed to one object.
Inside the class that defines the method, an accessible static method may be called without writing the class name. That shortcut works from another static method in the same class as well. From an unrelated class, keep the ClassName.method form.
// inside class RadioTower
public static void report() {
int level = watts();
System.out.println(level);
}
Here report and watts are both in RadioTower, so watts() is enough. Outside RadioTower, the same call would be written RadioTower.watts(). Later topics use other class calls such as Math.abs(n); this page is only about the ClassName.method pattern, not a Math catalog.
Key points
- A class method is static and belongs to the class, not to one constructed object.
- From another class, call ClassName.method(arguments), such as RadioTower.watts().
- Inside the defining class, you may omit the class name for an accessible static method.
- Omitting the class name is not allowed from an unrelated class.
Omitting the class name is allowed only inside the same class that defines the static method. From a different class, write ClassName.method(...). A class method call still does not require, or target, one constructed object.