Created
April 17, 2012 20:51
-
-
Save iande/2408971 to your computer and use it in GitHub Desktop.
Why instanceof Is the Devil.
This file contains hidden or 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
public class Triangle { | |
public int width; | |
public int height; | |
} | |
public class Rectangle { | |
public int width; | |
public int height; | |
} | |
public class Circle { | |
public int radius; | |
} | |
public class AreaReporter { | |
public void printArea(Object shape) { | |
double area = 0; | |
if(shape instanceof Triangle) { | |
area = 0.5 * ((Triangle)shape).width * ((Triangle)shape).height; | |
} else if(shape instanceof Rectangle) { | |
area = 1.0 * ((Rectangle)shape).width * ((Rectangle)shape).height; | |
} else if(shape instanceof Circle) { | |
area = Math.PI * ((Circle)shape).radius; | |
} | |
System.out.println("The area is: " + area); | |
} | |
} | |
public class Main | |
public static void main() { | |
AreaReporter reporter = new AreaReporter(); | |
Circle x = new Circle(); | |
x.radius = 10; | |
Triangle y = new Triangle(); | |
y.width = 10; | |
y.height = 5; | |
Rectangle z = new Rectangle(); | |
z.width = 10; | |
z.height = 5; | |
reporter.printArea(x); | |
reporter.printArea(y); | |
reporter.printArea(z); | |
} | |
} |
This file contains hidden or 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
public interface HasArea { | |
double getArea(); | |
} | |
public class Triangle implements HasArea { | |
public int width; | |
public int height; | |
public double getArea() { return 0.5 * width * height; } | |
} | |
public class Rectangle implements HasArea { | |
public int width; | |
public int height; | |
public double getArea() { return 1.0 * width * height; } | |
} | |
public class Circle implements HasArea { | |
public int radius; | |
public double getArea() { return Math.PI * radius; } | |
} | |
public class AreaReporter { | |
public void printArea(HasArea shape) { | |
System.out.println("The area is: " + shape.getArea()); | |
} | |
} | |
public class Main | |
public static void main() { | |
AreaReporter reporter = new AreaReporter(); | |
Circle x = new Circle(); | |
x.radius = 10; | |
Triangle y = new Triangle(); | |
y.width = 10; | |
y.height = 5; | |
Rectangle z = new Rectangle(); | |
z.width = 10; | |
z.height = 5; | |
reporter.printArea(x); | |
reporter.printArea(y); | |
reporter.printArea(z); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment