Monday, February 16, 2026

Does This Compile?

When I was teaching at Sun Microsystems (2000-2002), I created the example below for my Java classes. Around day 3 or 4 I would start writing it on the whiteboard piece-by-piece and asking "does this compile?" Then I'd proceed to walk the students through why it worked. The point was to show how identifiers are resolved, and then show things that would conflict and why.

What’s changed is I added a little generic static method to add to the fun (they weren’t in the language when I taught).

class x {
    static x x = new x();
    x() { }
    x x(x x) {
        return x;
    }
    static <x> x x(x x) {
        return x;
    }
    public static void main(String[] args) {
        x x = new x();
        System.out.println(x.<String>x("x"));
    }
}

This code compiles and, when run, prints:

x

No comments:

Post a Comment