Class Methods: Behavior

Class Methods: Behavior in Java: The grinding bay at a machine shop is behind a wall, and the only way in is a hatch with a shelf.

The Analogy: The Job Card And The Hatch At The Grinding Bay

The grinding bay at a machine shop is behind a wall, and the only way in is a hatch with a shelf. You do not walk in, you do not lean over and explain, and you cannot hear yourself over the noise anyway. What you do is fill in a job card -- printed fields, one line each: target diameter, surface finish, which shelf the part is sitting on -- put the card on the shelf and push it through. Somebody in there reads exactly what is on the card and nothing else. If a field is blank, they do not guess; if the card has no field for "leave the chamfer alone", that instruction does not exist as far as the bay is concerned. The printed fields are the whole vocabulary of the request.

Something comes back out of the hatch, and what comes back is the only thing you can build on. Some jobs hand you a measurement slip with a number on it. Some hand you nothing at all, and the point of the job was that the world changed -- the part is now in the finished rack, and you are expected to go and look. The foreman's rule is blunt: what comes through the hatch is the answer. Whatever the bay wrote on its own paperwork, whichever grinder they used, how many times they re-measured -- none of that is yours, and none of it is any of your business.

Here is the part that catches people. When the card goes through the hatch, the bay copies it onto their own docket and works from the copy. That is a genuine copy, and it protects you in one specific case: the target diameter field says 100, and if the grinder crosses out 100 and writes 98 on his docket, your card still says 100 and your records are intact. But the shelf-location field is different in kind. Your card says the part is on shelf B7, their docket says the part is on shelf B7, and there is exactly one part on shelf B7. When the bay walks out to B7 and takes half a millimetre off, your part has changed and your card is still pristine. Same copying rule, opposite outcome, and the difference is only ever whether the field holds the thing or holds where the thing is.

The failure mode is a crossed-out shelf number. A card comes in for B7; the bay decides B7 is the wrong shelf, crosses it out on their docket, writes C2, walks to C2, grinds that part to a beautiful finish and pushes the card back through. Your card still says B7. You collect the part from B7, it is untouched, and the shop is genuinely confused because they did the work and can show you the docket. Nobody lied and nothing was recorded wrongly -- the bay simply changed their copy of a location and expected that to reach you. The same shape shows up in two other ways worth naming now: two hatches with identical signs above them that differ only in which fields their cards accept, so a slightly ambiguous card gets handled by the wrong bay; and a hatch whose sign says "Measurement" but which quietly bumps the shift counter every time you use it, so the counter ends up measuring how often people asked rather than how much work was done.


Syntax or Core Structure

A method declaration has four parts before the body: modifiers, a return type, a name, and a parenthesised parameter list. The body either produces a value with return or produces nothing and is declared void. Everything else -- overloading, static, variable arity -- is a variation on those four parts.

public class Grinder {
    private int jobsDone;

    // Takes two values, returns one. Also changes state.
    int grind(int diameterMm, int passes) {
        jobsDone++;
        return diameterMm - passes;
    }

    // Overload: same name, different parameter list, delegates to the other one.
    int grind(int diameterMm) {
        return grind(diameterMm, 1);
    }

    // void: no value comes back, the effect is the point.
    void reset() {
        jobsDone = 0;
    }

    // A query: returns state, changes nothing.
    int jobsDone() {
        return jobsDone;
    }

    // static: belongs to the class, needs no instance, cannot touch jobsDone.
    static int passesFor(int fromMm, int toMm) {
        return fromMm - toMm;
    }

    // Variable arity: callers may pass zero or more ints.
    static int total(int... values) {
        int sum = 0;
        for (int v : values) {
            sum += v;
        }
        return sum;
    }

    public static void main(String[] args) {
        Grinder g = new Grinder();

        int a = g.grind(100, 3);
        int b = g.grind(80);

        System.out.println("a         " + a);
        System.out.println("b         " + b);
        System.out.println("jobs      " + g.jobsDone());
        System.out.println("passes    " + Grinder.passesFor(100, 96));
        System.out.println("total 0   " + Grinder.total());
        System.out.println("total 3   " + Grinder.total(4, 5, 6));

        g.reset();
        System.out.println("after     " + g.jobsDone());
    }
}

Output:

a         97
b         79
jobs      2
passes    4
total 0   0
total 3   15
after     0

Read the two grind calls together. g.grind(100, 3) matched the two-parameter version directly. g.grind(80) matched the one-parameter version, which called the two-parameter version with passes fixed at 1 -- which is why jobs reads 2 and not 3. The arithmetic lives in exactly one method and the overload is a convenience wrapper over it, which is the only version of overloading that does not eventually drift out of agreement with itself.

reset and jobsDone are the two halves of the same field, and they are shaped differently on purpose. reset is void: nothing comes back, and the only way to observe that it worked is to ask again -- which is exactly what the last line does. jobsDone returns a value and touches nothing. Keeping those two jobs in separate methods is worth more than it looks, and the Real World Example below is a demonstration of what goes wrong when they are merged.

passesFor is static, so it is called through the class name and has no access to jobsDone -- there is no instance for it to belong to. total is static too, and its int... parameter is an int[] that the compiler builds at the call site: total() gets an array of length zero, so the loop never runs and the answer is 0 rather than an error.


Technical Depth: What A Signature Actually Is, What Gets Copied At The Call, And How The Compiler Chooses Between Two Methods Of The Same Name

The signature is the name and the parameter types, and nothing else

A method's signature is a narrower thing than its declaration. It is the name plus the number, order and types of the parameters. Everything else in the declaration line is real, meaningful, and not part of the signature -- which decides what you are allowed to overload on.

Part of the declarationIn the signature?What follows from that
The method nameYesTwo methods may share a name only if their parameter lists differ
Number, order and types of parametersYesSwapping two parameters of different types creates a legal overload
Parameter namesNoRenaming a parameter breaks no caller and is not a source-compatible concern
Return typeNoTwo methods differing only in return type do not compile, ever
The throws clauseNoYou cannot overload on which exceptions a method declares
Access modifierNoYou cannot have a public and a private version of the same signature
staticNoA static and an instance method with the same signature clash

The return-type row is the one that surprises people. int read() and String read() in the same class is not an overload, it is a compile error, because the compiler resolves a call before it knows what you intend to do with the result -- and read(); on a line by itself gives it nothing to work from.

Every argument is copied; the only question is what was in the variable

Java passes arguments by value, with no exceptions and no syntax to opt out. What trips people up is that the value in a variable of reference type is not the object, it is a reference to the object -- so the copy is a second reference to the same object.

public class Copies {
    static void bump(int n) {
        n = n + 1;                      // changes this method's copy
    }

    static void addTo(StringBuilder sb) {
        sb.append("-edited");           // reaches the caller's object
    }

    static void replace(StringBuilder sb) {
        sb = new StringBuilder("brand new");   // repoints this method's copy
        sb.append("!");                        // edits the new one, invisibly
    }

    public static void main(String[] args) {
        int count = 5;
        bump(count);
        System.out.println("count     " + count);

        StringBuilder held = new StringBuilder("original");
        addTo(held);
        System.out.println("appended  " + held);

        replace(held);
        System.out.println("replaced  " + held);
    }
}

Output:

count     5
appended  original-edited
replaced  original-edited

bump and replace are the same mistake wearing different clothes: both assign to a parameter, and an assignment to a parameter is only ever visible inside the method. addTo never assigns to anything -- it follows the reference and changes what it finds -- which is why it is the only one of the three the caller can see.

What the method does to a parameterCaller sees it?Why
Assigns a new number to an int parameterNoThe parameter is a separate variable holding a copy of the number
Assigns a new object to a reference parameterNoThe parameter is a separate variable holding a copy of the reference
Calls a mutating method on the referenced objectYesBoth references lead to one object, and that object changed
Assigns to a field of the referenced objectYesSame reason -- the field belongs to the shared object, not to the parameter
Mutates an element of a passed arrayYesAn array is an object; the brackets are field access with a computed name

The practical consequence is that "pass by value" gives you no protection at all where you most want it. A method handed a List, an array or any mutable object has been handed the real thing, and the only defences are an unmodifiable view, a copy taken at the boundary, or an immutable type.

Overload resolution happens at compile time, in three phases, from static types

When two or more methods share a name, the compiler picks one before the program runs, using only the declared types of the argument expressions. It tries three passes in order and stops at the first pass that finds any applicable method.

public class Choose {
    static String take(int v)     { return "int"; }
    static String take(long v)    { return "long"; }
    static String take(double v)  { return "double"; }
    static String take(Integer v) { return "Integer"; }
    static String take(Object v)  { return "Object"; }

    public static void main(String[] args) {
        byte small = 7;
        Object boxedInt = Integer.valueOf(9);

        System.out.println("byte      " + take(small));
        System.out.println("int       " + take(42));
        System.out.println("long      " + take(42L));
        System.out.println("float     " + take(1.5f));
        System.out.println("Integer   " + take(Integer.valueOf(9)));
        System.out.println("as Object " + take(boxedInt));
        System.out.println("String    " + take("text"));
    }
}

Output:

byte      int
int       int
long      long
float     double
Integer   Integer
as Object Object
String    Object

The two middle lines are the whole lesson. take(Integer.valueOf(9)) and take(boxedInt) hand over the very same kind of object, and they reach different methods, because the compiler read Integer in one case and Object in the other. Overloading is chosen by what the compiler can see; it is not overriding, and it never consults the object at run time.

PhaseConversions it allowsAn argument that needs this phase
1 -- strictIdentity, widening primitive, widening referenceA byte reaching take(int)
2 -- looseEverything in phase 1, plus boxing and unboxingAn int reaching a class that only declares take(Object)
3 -- variable arityEverything in phase 2, plus packing arguments into an arrayThree int arguments reaching total(int...)

Two consequences follow from the ordering. A variable-arity method is a last resort, so adding total(int...) next to total(int, int) never steals the two-argument call. And within a phase, the most specific applicable method wins -- byte widens to int, long and double alike, and int wins because int itself widens to the other two. When no candidate is more specific than the rest, the call is rejected as ambiguous rather than guessed at.

The receiver is evaluated even when it is not used

An instance call needs an object; a static call does not. Writing a static call as though it were an instance call is legal, and the result is a line that looks like it must dereference and does not.

public class Receiver {
    static String kind() {
        return "static";
    }

    String name() {
        return "instance";
    }

    public static void main(String[] args) {
        Receiver r = null;

        System.out.println("static    " + r.kind());   // legal, no dereference

        boolean threw = false;
        try {
            System.out.println(r.name());
        } catch (NullPointerException e) {
            threw = true;
        }
        System.out.println("threw     " + threw);
    }
}

Output:

static    static
threw     true

r.kind() resolved to Receiver.kind() at compile time. The expression r is still evaluated -- it just produces null, which is then discarded, because a static method has no receiver to be null. r.name() does need one, and fails at the call. Write static calls through the class name and this whole category of confusion disappears.

The mirror-image rule is the one the compiler enforces loudly: a static method has no this, so it cannot read an instance field or call an instance method without being handed an object first. That is not a restriction on what statics may do, it is a statement of what they are -- behaviour that belongs to the class rather than to any one object.


Real World Example: A Payroll Run Where Every Step Is A Method And One Of Them Lies About What It Does

A timesheet is a good test of method design because the calculation genuinely decomposes: minutes add up, overtime is minutes above a threshold, and pay is a rate applied to both bands. Each of those is one question with one answer, so each becomes a method that returns a value and the next one calls it. This version works, produces the right numbers, and contains a bug that no test of its return values can find.

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class Timesheet {
    static final int STANDARD_MINUTES = 2400;   // 40 hours

    private final String worker;
    private final int rateP;                    // pence per hour
    private final List<Integer> entries = new ArrayList<>();
    private int auditCount;

    Timesheet(String worker, int rateP) {
        this.worker = worker;
        this.rateP = rateP;
    }

    // void: exists for its effect
    void log(int minutes) {
        entries.add(minutes);
    }

    int totalMinutes() {
        int sum = 0;
        for (int m : entries) {
            sum += m;
        }
        return sum;
    }

    int overtimeMinutes() {
        return Math.max(totalMinutes() - STANDARD_MINUTES, 0);
    }

    // Reads like a question. Also bumps auditCount. That is the bug.
    int grossPence() {
        auditCount++;
        int plain = Math.min(totalMinutes(), STANDARD_MINUTES);
        int over = overtimeMinutes();
        return (plain * rateP + over * rateP * 3 / 2) / 60;
    }

    // Overload: same question, one more input, delegates rather than duplicates.
    int grossPence(int bonusP) {
        return grossPence() + bonusP;
    }

    int auditCount() {
        return auditCount;
    }

    String worker() {
        return worker;
    }

    public static void main(String[] args) {
        Timesheet a = new Timesheet("A-Ellis", 1500);
        a.log(480);
        a.log(480);
        a.log(480);
        a.log(480);
        a.log(480);

        Timesheet b = new Timesheet("B-Nkomo", 1500);
        b.log(540);
        b.log(540);
        b.log(480);
        b.log(480);
        b.log(600);

        Timesheet c = new Timesheet("C-Ruiz", 1500);
        c.log(300);
        c.log(240);

        List<Timesheet> sheets = new ArrayList<>();
        sheets.add(a);
        sheets.add(b);
        sheets.add(c);

        int payroll = 0;
        for (Timesheet t : sheets) {
            int gross = t.grossPence();         // called once, held in a local
            payroll += gross;
            System.out.println(String.format(Locale.ROOT,
                    "%-8s mins %4d  over %3d  gross %6d",
                    t.worker(), t.totalMinutes(), t.overtimeMinutes(), gross));
        }

        System.out.println("workers   " + sheets.size());
        System.out.println("payroll   " + payroll);
        System.out.println("audits a  " + a.auditCount());

        int once = c.grossPence();
        int twice = c.grossPence();
        System.out.println("stable    " + (once == twice));
        System.out.println("audits c  " + c.auditCount());
        System.out.println("bonus     " + c.grossPence(2500));
        System.out.println("audits c2 " + c.auditCount());
        System.out.println("standard  " + STANDARD_MINUTES);
    }
}

Output:

A-Ellis  mins 2400  over   0  gross  60000
B-Nkomo  mins 2640  over 240  gross  69000
C-Ruiz   mins  540  over   0  gross  13500
workers   3
payroll   142500
audits a  1
stable    true
audits c  3
bonus     16000
audits c2 4
standard  2400

The decomposition is the part worth copying. overtimeMinutes calls totalMinutes, grossPence calls both, and none of them knows or cares who else is calling. Each returns its answer instead of printing it, which is why the loop can put three of them on one formatted line and add one of them to a running total in the same breath. log is the odd one out and is deliberately shaped differently: it returns void because there is no answer to give, only an effect, and the way you check that it worked is to ask totalMinutes afterwards.

Note the local variable in the loop. int gross = t.grossPence(); is called once and used twice -- once for the printed row and once for the payroll total. Writing t.grossPence() in both places would read more naturally and would be a real defect here, because the second call would be a second increment of auditCount. That is a bad reason to need a local variable, and the fact that this program needs one is the first clue that something is wrong. The overload is better behaved: grossPence(int) does not recompute anything, it calls grossPence() and adds, so the pay formula exists in one place and a change to the overtime multiplier cannot leave the two versions disagreeing.

Now the bug, stated plainly. grossPence has the name of a question and the body of a command: it increments auditCount every time anyone asks what the pay is. The output proves how well this hides. once == twice is true, so the return value is perfectly stable and no assertion on the returned number will ever fail; meanwhile audits c reads 3, and two of those three came from the diagnostic lines that computed once and twice in order to check the value was stable. Then grossPence(2500) pushed it to 4 from a call site that mentions nothing but a bonus. Every caching getter, every lazily-initialised accessor and every "let me just count the reads" counter is this same shape, and it is the most expensive category of method bug precisely because the visible answer stays correct.

The honest limits. The design flaw is that auditCount cannot mean anything: it counts calls, so it measures the shape of the calling code rather than the payroll -- a retry, an extra log line, a debugger stepping over the expression, or a switch from one call to a cached local all change it, and none of those are audits. The count belongs to whatever actually performs an audit, and the fix is a separate recordAudit() that a caller invokes on purpose. Beyond that: log validates nothing, so a negative entry or a 100000-minute typo is accepted in silence and simply moves the total; grossPence truncates twice, at * 3 / 2 and again at / 60, so each worker can lose up to a penny and the payroll total is not the sum of a decimal calculation -- money should be computed in whole pence with the division done last, or not in int at all; overtime is measured against the whole timesheet rather than per day, which is not how most overtime rules are actually written, so a worker with one 14-hour day and a short week is paid as though nothing unusual happened; and rateP is final, so a rate change part-way through a period cannot be represented at all and the only workaround is two timesheets that no longer add up to one worker.


Common Mistakes

  1. Trying to overload on the return type. int find() and String find() in one class is a compile error, not a choice. Return type is not part of the signature, so give the two methods different names.
  1. Assigning to a parameter and expecting the caller to see it. void bump(int n) { n++; } changes nothing outside the method. If the caller needs a new value, return it and let them assign.
  1. Assuming an object argument is safe. Handing a method a List or an array hands it the real one. Pass an unmodifiable view, a copy, or an immutable type -- "pass by value" protects the variable, never the object.
  1. Printing inside a method that should return. void showTax() can only be used from a console and can only be tested by capturing output. Return the number and let the caller decide whether to print it.
  1. A query that mutates. Any getter, accessor or isSomething that caches, counts, lazily builds or logs has become a command wearing a question's name, and its return value will keep looking right.
  1. Expecting overload resolution to use the runtime type. Object o = "text"; take(o); calls take(Object) even though the object is a String. Overloading is decided by the compiler from declared types; only overriding consults the object.
  1. Confusing static and instance context in either direction. A static method reading an instance field will not compile, and calling an instance method from main without an object will not either. The fix is always to say which object you mean.
  1. Overloads separated only by boxing. On a List<Integer>, remove(1) calls remove(int index) and remove(Integer.valueOf(1)) calls remove(Object). Both compile, they do completely different things, and the difference is invisible at a glance.
  1. A long run of parameters of the same type. transfer(int from, int to, int amount, int fee) will eventually be called with two arguments transposed, and it will compile, run, and be wrong. Fewer parameters, or a type per role.

Best Practices

  • One job per method, and let the name say which job. If the honest name needs the word "and", you have two methods. totalMinutes and overtimeMinutes stayed separate for exactly this reason.
  • Separate commands from queries. A method that returns a value should leave observable state alone; a method that changes state should be void and be named with a verb of action. Mixing them produces bugs that pass their own tests.
  • Return results, do not print them. A method that returns a value can be printed, summed, formatted, cached and asserted on. One that prints can only be watched.
  • Keep parameter lists short and their types distinct. Two or three parameters is comfortable; four of the same primitive type is a transposition waiting to happen, and usually a sign that some of them belong together in an object.
  • Overload only when the methods answer the same question. grind(int) and grind(int, int) differ in how much the caller specifies, not in what they mean. When the meaning differs, use a different name -- the compiler will let you overload, the reader will not thank you.
  • Make overloads delegate to one real implementation. Duplicated arithmetic between two overloads stays in agreement exactly until the first change to one of them.
  • Default to private and widen only when something outside needs it. The public methods are the contract you cannot quietly change; totalMinutes being public is a promise, private would have kept it an internal detail.
  • Call static methods through the class name. Timesheet.STANDARD_MINUTES and Grinder.passesFor(...) say out loud that no object is involved, and they make the null-receiver oddity impossible to write by accident.

Practice Exercises

  1. The Honest Getter. Remove auditCount++ from grossPence() and add a separate void recordAudit(). Prove the split works: compute the gross ten times in a loop and print auditCount (it must be 0), then call recordAudit() three times and print it again. Finally, write one sentence explaining why stable true in the original output was never going to catch the bug, and name one other method in the class you would have to check for the same shape.
  1. The Parameter That Would Not Change. Write three methods and show what each one can and cannot do. static void raise(int rateP) that assigns rateP = rateP + 100; static void raise(Timesheet t) that calls t.log(60); and static void swap(Timesheet t) that assigns t = new Timesheet("Z-Temp", 9999) and then logs 60 to it. Call all three from main, print the rate and the total minutes after each, and state the single rule that explains all three results.
  1. The Two Removes. Build two identical List<Integer> values holding 10, 20 and 30. Call remove(1) on the first and remove(Integer.valueOf(1)) on the second, print both lists and both return values, and explain which overload each call selected and which resolution phase chose it. Then rewrite both calls so that a reader can tell at a glance which one is meant.