Skip to content

Instantly share code, notes, and snippets.

@GeePawHill
Last active June 6, 2022 14:36
Show Gist options
  • Select an option

  • Save GeePawHill/23669f85377b81a9cf5f2694ed495e6b to your computer and use it in GitHub Desktop.

Select an option

Save GeePawHill/23669f85377b81a9cf5f2694ed495e6b to your computer and use it in GitHub Desktop.
A classic "switch on type" in Java. The draw method interrogates its parameter's class, and decides what to do as a resuilt.
interfact Thing { }
class Wall implemnts Thing { }
class Door implements Thing { }
class Chest implements Thing { }
void draw(Thing thing) {
if(thing instanceof(Wall) drawWall(thing)
else if(thing instanceof(Door) drawDoor(thing)
else if(thing instanceOf(Chest) drawChest(thing)
else drawBlank(thing)
}
This is a switch on type, too. This time, it decided what to do not based on the particular sub-class of Thing, but on a type field inside Thing.
class Thing {
public final int kind;
}
void draw(Thing thing) {
switch(thing.kind) {
case WALL: drawWall(thing); break;
case DOOR: drawDoor(thing); break;
case CHEST: drawChest(thing); break;
default: drawBlank(thing)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment