Warm-up

Predict eight lines

5 minfresher05 yrs

One concept, guided. Near-impossible to fail.

What this teaches

  • Overloads are chosen by the compiler from the declared type
  • Overrides are chosen by the JVM from the runtime type
  • A static method is hidden, not overridden, and follows the reference
  • Fields are not polymorphic either

Starter

Starter.javaOpen in playground
import java.util.*;

/**
 * WARM-UP — 5 minutes. One concept. Hard to fail.
 *
 * Eight lines. Most people get five right and are surprised by three.
 *
 * TASKS
 *   1. Write down all eight predictions BEFORE running. Actually write them.
 *   2. Run it.
 *   3. For every one you got wrong, work out which of the two rules applies:
 *        - the compiler chose, from the DECLARED type
 *        - the JVM chose, from the RUNTIME type
 *   4. In a comment: which lines would change if `ref` were declared Child?
 */
public class Starter {

    static String describe(Object o) { return "describe(Object)"; }

    static String describe(String s) { return "describe(String)"; }

    static class Parent {
        static String tag() { return "Parent.tag()"; }

        String name() { return "Parent.name()"; }

        String label = "Parent.label";
    }

    static class Child extends Parent {
        static String tag() { return "Child.tag()"; }

        @Override String name() { return "Child.name()"; }

        String label = "Child.label";
    }

    public static void main(String[] args) {
        Object held = "I am really a String";
        String plain = "an ordinary String";

        System.out.println("1  " + describe(held));
        System.out.println("2  " + describe(plain));
        System.out.println("3  " + describe((String) held));
        System.out.println("4  " + describe(null));

        Parent ref = new Child();

        System.out.println("5  " + ref.name());
        System.out.println("6  " + ref.tag());
        System.out.println("7  " + ref.label);
        System.out.println("8  " + ((Child) ref).label);

        // Question to answer in a comment before you move on:
        // Line 1 and line 3 pass the SAME object. Why do they differ?
        // Nothing about the object changed between them.
    }
}

Run it locally:

cd exercises/java/oop/overloading-vs-overriding/01-warmup
javac Starter.java -d /tmp/out && java -cp /tmp/out Starter

Done when

  • You wrote down all eight predictions before running
  • A comment states the one-sentence rule that explains every line you got wrong
  • You can say which lines would change if the variable were declared Child

← Back to What is the difference between overloading and overriding?