Calling Class Methods
Some methods belong to a class itself, and a program calls them through the class's name. The class below works out how much paint a job needs.
public class Paint
{
public static int liters(int rooms)
{
return 4 * rooms;
}
public static int twoCoats(int rooms)
{
return 2 * liters(rooms);
}
}
The static keyword
Both headers have the keyword
static before the return type and the method name. It marks each one as a class method, a method that belongs to the Paint class itself. A program doesn't need a Paint object to use it, and later lessons show methods that do need one.Only
static decides this. A header with void or double in place of int still declares a class method, as long as static is there.Calling with the class name
A program in another class, say one named
Job, calls the method with the class name, a dot, and then the method name and its arguments.int needed = Paint.liters(3) + 1;
System.out.println(needed);
The call
Paint.liters(3) runs the method with rooms equal to 3, and it returns 12. The call is an expression, so its value can be added to: the extra liter for touch-ups makes needed equal to 13, and the segment prints 13.Calls inside the class
The method
twoCoats calls liters without writing Paint. in front of it. Inside the class that declares a method, the class name is optional. A method name written there is looked up in that same class. Writing Paint.liters(rooms) there would work the same way.System.out.println(Paint.twoCoats(3));
From
Job, this call runs twoCoats with rooms equal to 3. Its body calls liters(3), which returns 12, and then it returns twice that, so the line prints 24.Outside
Paint the name isn't optional. In Job, the statement int n = liters(3); doesn't compile, since Job has no method named liters and the call doesn't say which class to look in.