Created
February 8, 2015 21:24
-
-
Save kevinpet/ff851696253382ecc2c9 to your computer and use it in GitHub Desktop.
Java instanceof
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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