[munich-lisp] multimethods, generic functions, multiple dispatch, ...

Christian Schuhegger Christian.Schuhegger at gmx.de
Sun Sep 11 14:48:49 UTC 2005


Andreas Hauser wrote:
>>(defmethod do-shapes-collide-p ((shape1 Triangle) (shape2 Circle))
>>   (...))
>>(defmethod do-shapes-collide-p ((shape1 Circle)   (shape2 Triangle))
>>   (do-shapes-collide-p shape2 shape1))
>>(defmethod do-shapes-collide-p ((shape1 Triange)  (shape2 Square))
>>   (...))
>>...
> 
> 
> And why don't you need:
> (defmethod do-shapes-collide-p ((shape1 Circle) (shape2 Triangle))
> ?

this is because collission of two objects is symmetric:
  a collides with b <=> b collides with a
and i do not have to implement the same code again.

> It must be serialized somewhere (in Object World ?). Do the collision there.

this is why i suggested:
>  probably it is best factored out in a third CollisionDetectionAlgorithm class which only contains static methods for each combination of shapes. 

and you are right:
> But it seems Java can do methods with different sigantures:
> 
> public class foo
> {
>     public foo()
>     {
>     }
> 
>     public void bar(int i)
>     {
>         System.out.println(i + 1);
>     }
> 
>     public void  bar(String s)
>     {
>         System.out.println(s + " world");
>     }
> 
>     public static void main(String args[])
>     {
>         foo f = new foo();
>         f.bar(12);
>         f.bar("Hello");
>     }
> }

but this overloading of methods is something "compile time" and not "run 
time", e.g. if you would have some code similar like this:
-- snip start --
public class CollisionDetectionAlgorithm {
     public static boolean collides(Shape s1, Shape s2) {...;}// throw a 
runtime exception
     public static boolean collides(Triangle s1, Circle s2) {...;}
     public static boolean collides(Triangle s1, Square s2) {...;}

     public static void main(String[] args) {
	Shape s1 = new Triangle();
	Shape s2 = new Circle();
	System.out.println(collides(s1,s2));
     }
}
-- snip end --
you would end up with the first collides method being called which would 
throw a runtime exception. the only runtime type polymorphism that java 
knows is subtype type polymorphism which only reacts on the type of the 
implicite 'this' type. the calls to the overloaded methods are fixed at 
compile time.
-- 
Christian Schuhegger
http://www.el-chef.de/



More information about the munich-lisp mailing list