Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Object-Oriented Programming

    Quick Reference

    Glossary and cheat sheet for Object-Oriented Programming — the page to reread before an interview.

    Extra: Reference8 min read

    Glossary#

    TermPlain meaningChapter
    encapsulationhide data; expose rule-enforcing methods1
    invarianta rule that must always hold for an object1
    private / package-private / protected / publicclass / package / package + subclasses / everyone1
    getter / settermethod that reads / writes a field1
    inheritance / extendsreuse and extend a class ("is-a")2
    superclass / subclassparent / child2
    super(...) / super.m()call parent constructor / parent's method2, 3
    Objectthe root class of all Java classes2
    single inheritancea class extends only one class2
    overriding / @Overridesubclass replaces an inherited method / compiler check3
    covariant returnoverriding method may return a subtype3
    overloading vs overridingdifferent params, compile time / same params, run time3
    polymorphismone call, behaviour depends on the actual object4
    declared type / actual typewhat the compiler knows / what the object really is4
    dynamic dispatch / vtablechoosing the method at run time / per-class method table4
    upcast / downcast / ClassCastExceptionto parent (safe) / to child (checked) / invalid downcast4
    instanceof patternif (x instanceof T t) test-and-bind4
    stack frame / heapa method's private notepad for locals / shared area where all objects live4
    object headerhidden start of every object; points to its class4
    invokevirtual / invokeinterfacebytecode calls whose version is chosen at run time4
    static binding / dynamic bindingmethod fixed at compile time / chosen at run time4
    monomorphic / megamorphic call sitethe JIT saw one type there / many types4
    ArrayStoreExceptionstoring the wrong type into a covariant array4
    tell, don't askcall an overridden method instead of checking types4
    abstractionexpose what, hide how5, 6
    abstract class / abstract methodcan't instantiate / no body, must be implemented5
    template methodparent defines steps; subclasses fill in some5
    interface / implementscontract ("can-do") / signing it6
    default / static interface methodinherited body / utility on the interface6
    diamond problemambiguity from two parents with the same member6
    programming to an interfacedepend on the interface type, not the class6
    composition / delegation"has-a" fields / forwarding work to them7
    fragile base classparent changes breaking subclasses7
    equals/hashCode contractequal objects ⇒ equal hash codes8
    hash collisionunequal objects, same hash code8
    static / instance initializerruns once per class / per object9
    final class / final methodcan't be extended / overridden9
    static nested / inner / anonymous classindependent helper / tied to outer object / unnamed one-off10
    enum / values() / ordinal()fixed set of instances / all of them / position11
    record / compact constructorone-line immutable data class / its validation block12

    Cheat Sheet#

    Templates

    Java
    abstract class Base {                               interface Capability {
        protected final int x;                              int must();
        Base(int x) { this.x = x; }                         default String nice() { return "v" + must(); }
        abstract int step();                            }
        int run() { return step() * 2; }
    }
    class Impl extends Base implements Capability {
        Impl() { super(1); }
        @Override int step() { return x + 1; }
        @Override public int must() { return 42; }
    }
    record Cell(int r, int c) {}                        enum Level { LOW, MID, HIGH }

    equals / hashCode

    Java
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Point p)) return false;
        return x == p.x && y == p.y;
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    } // same fields as equals
    // or just:  record Point(int x, int y) {}

    Decision rules

    Output
      data private, behaviour public · meaningful methods > raw setters
      interface for the type others depend on · abstract class only for shared state/code
      composition by default · inheritance only for stable, substitutable is-a
      override equals ⇒ override hashCode · immutable keys · records for data
      many instanceof checks ⇒ move behaviour into overridden methods
      nested classes static unless they need the outer object

    Try This Yourself#

    1. Add a question type. Add FillInTheBlank (correct if the answer matches any of several accepted words) to the quiz example. Confirm the grading loop needed zero changes.

    2. Break the contract on purpose. Write record Cell(int r, int c) {} and a normal class CellClass with only equals overridden. Put (2, 3) into a HashSet of each and check contains(new ...(2, 3)). Then add hashCode to the class and try again.

    3. Composition drill. Implement Timer as NoLimitTimer and CountdownTimer(int seconds), and Proctor as NoProctor and TabSwitchProctor. Build four different quizzes from these parts without creating any new Quiz subclasses.

    4. Explain out loud (2 minutes each, recorded): the four pillars; abstract class vs interface; why @Override matters.