Skip to content

Instantly share code, notes, and snippets.

@kevinpet
Created February 8, 2015 21:24
Show Gist options
  • Save kevinpet/ff851696253382ecc2c9 to your computer and use it in GitHub Desktop.
Save kevinpet/ff851696253382ecc2c9 to your computer and use it in GitHub Desktop.
Java instanceof
abstract class BadFoo {
static class Bar extends BadFoo {
int bar;
private Bar(int bar) {
this.bar = bar;
}
}
static class Baz extends BadFoo {
String baz;
private Baz(String baz) {
this.baz = baz;
}
}
static void handle(BadFoo f) {
if (f instanceof Bar) {
Bar b = (Bar) f;
System.out.println("I have " + b.bar + " bars");
} else if (f instanceof Baz) {
Baz b = (Baz) f;
System.out.println("I have the " + b.baz + " baz");
}
}
public static void main(String[] args) {
handle(new Bar(42));
handle(new Baz("Luhrmann"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment