1.10 - Calling Class Methods
Class methods belong to the class itself, not to individual objects made from that class. You can spot them by the keyword
static in the method header.You typically call a class method using the class name plus the dot operator. If you’re calling it from inside the same class where it’s defined, you can actually skip the class name.
public class MathHelper { static int square(int x) { return x * x; } } int result = MathHelper.square(5); // calling from outside the class
Inside the class where a class method is written, you can leave off the class name:
public class Temperature { public static double toCelsius(double fahrenheit) { return (fahrenheit - 32) * 5 / 9; } public static void printCelsius(double fahrenheit) { double c = toCelsius(fahrenheit); // same class, so no class name needed System.out.println(c); } }
From any other class, you need the class name:
double boiling = Temperature.toCelsius(212.0); // 100.0 Temperature.printCelsius(50.0); // prints 10.0 double c = toCelsius(98.6); // won't compile here, Java doesn't know which class toCelsius is in
You don’t need an object to call a class method. All the
Math methods are class methods, which is why you write Math.abs(-5) and never create a Math object.