Static methods in Java
Overloading stands in for the default parameters Java never got.
System.out.println(Greeter.hello("Ada"));
System.out.println(Greeter.hello("Grace", true));
System.out.println(Greeter.area(3, 4));
class Greeter {
// Java overloads instead of defaulting parameters
static String hello(String name) { return hello(name, false); }
static String hello(String name, boolean shout) {
var text = "hello, " + name;
return shout ? text.toUpperCase() : text;
}
static double area(double width, double height) {
return width * height / 2;
}
}
How it works
- The one-argument
helloforwards to the two-argument version. - Overloads share a name and differ by signature.
- Classes can sit below the code that calls them in the same file.
Keywords and builtins used here
Greeterareabooleanclassdoublehelloreturnstaticvar
The run, in numbers
- Lines
- 17
- Characters to type
- 469
- Tokens
- 123
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 82 seconds.
Step 1 of 3 in Methods & lambdas, step 15 of 29 in Language basics.