This is a lightning talk I gave at an internal event called Techquilla in ThoughtWorks Pune office.
More details: http://www.wikyblog.com/AmanKing/Multimethods
7. public class MultimethodsDemo { static class Walk { } static class Dance { } static class Attack { } static class Robot { public String doThis(Walk walk) { return "I am walking..."; } public String doThis(Dance dance) { return "Let's boogie woogie..."; } public String doThis(Attack attack) { throw new RuntimeException("I don't believe in violence!"); } } public static void main(String[] args) { Robot robot = new Robot();System.out.println( robot.doThis( new Walk() ));System.out.println( robot.doThis( new Dance() ));System.out.println( robot.doThis( new Attack() )); }}
8. I am walking...Let's boogie woogie...Exception in thread "main" java.lang.RuntimeException: I don't believe in violence! at MultimethodsDemo$Robot.doThis(MultimethodsDemo.java:10) at MultimethodsDemo.main(MultimethodsDemo.java:18)
11. public class MultimethodsDemo { static class Walk { } static class Dance { } static class Attack { } static class Robot { public String doThis(Walk walk) { return "I am walking..."; } public String doThis(Dance dance) { return "Let's boogie woogie..."; } public String doThis(Attack attack) { throw new RuntimeException("I don't believe in violence!"); } } public static void main(String[] args) { Robot robot = new Robot();System.out.println( robot.doThis( new Walk() ));System.out.println( robot.doThis( new Dance() ));System.out.println( robot.doThis( new Attack() )); }}
12. import java.util.*;public class MultimethodsDemo {static interface Command {} static class Walk implements Command { } static class Dance implements Command { } static class Attack implements Command { } static class Robot { public String doThis(Walk walk) { return "I am walking..."; } public String doThis(Dance dance) { return "Let's boogie woogie..."; } public String doThis(Attack attack) { throw new RuntimeException("I don't believe in violence!"); } } public static void main(String[] args) { Robot robot = new Robot(); List<Command> commands = Arrays.asList( new Walk(), new Dance(), new Attack() );for ( Command command : commands ) {System.out.println( robot.doThis(command) ); } }}
18. Exception in thread "main" java.lang.RuntimeException: Unknown command: class MultimethodsDemo$Walk at MultimethodsDemo$Robot.doThis(MultimethodsDemo.java:15) at MultimethodsDemo.main(MultimethodsDemo.java:23)