Calling Class Methods from Documentation
A documentation table
A class written by someone else is usually known by its documentation, one row per method. A bakery's program uses the class
Bakery.public static int batches(int ovens)
the batches a day of baking yields, at 3 per oven
public static int loaves(int batches)
the loaves from that many batches, at 12 per batch
public static int loaves(int batches, int extra)
the loaves from that many batches, plus extra more
public static double flour(int count)
the kilograms of flour for that many loaves, at 0.5 per loaf
public static void schedule(int hour)
sets the hour the ovens start; returns no value
Each header gives the return type, the name, and the parameter list. The line under each header says what the method does, or what its returned value means.
The word
static says these are class methods, so a program in another class writes Bakery. before each name. In that other class, int n = loaves(3); doesn't compile, since the call doesn't say which class the method is in.Choosing between overloads
Two rows share the name
loaves, and the arguments decide which one runs. The call Bakery.loaves(3) has one int argument, so it runs the first, which returns 36. The call Bakery.loaves(3, 5) has two, so it runs the second and returns 41.A call has to fit one of the rows. In
Bakery.loaves(2.5) the argument is a double, which doesn't fit an int parameter, so neither row matches and the call doesn't compile.A call as an argument
An argument can be another call. Java evaluates the inner call first and passes its value to the outer one.
int made = Bakery.loaves(Bakery.batches(4));
System.out.println(made);
For four ovens,
Bakery.batches(4) returns 12. That 12 is the one argument of loaves, so the first loaves row runs and returns 144, and the segment prints 144.An inner call's return type has to suit the outer parameter, the same way a variable passed there would. Since
flour returns a double, Bakery.batches(Bakery.flour(10)) doesn't compile.Where a returned value goes
The method
schedule is void, so it's called as a statement by itself: Bakery.schedule(6); sets the ovens to start at 6. It has no value to store, and int h = Bakery.schedule(6); doesn't compile.A returned value has to fit the variable it's stored in. Since
flour returns a double, int kilos = Bakery.flour(36); doesn't compile. In the other direction an int value fits a double, so double lots = Bakery.loaves(3); compiles and stores 36.0.