Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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