Generic functions and multiple dispatch
Java has "single dispatch"
class DispatchDemo {
static class A {
void foo( B b ) {
System.out.println( "foo called on A B" );
}
void foo( SubB b ) {
System.out.println( "foo called on A SUB-B" );
}
}
static class SubA extends A {
void foo( B b ) {
System.out.println( "foo called on SUB-A B" );
}
void foo( SubB b ) {
System.out.println( "foo called on SUB-A SUB-B" );
}
}
static class B { }
static class SubB extends B { }
static public void main( String[] args ) {
A just_a = new A( );
B just_b = new B( );
A sub_a = new SubA( );
B sub_b = new SubB( );
just_a.foo( just_b );
just_a.foo( sub_b );
sub_a.foo( just_b );
sub_a.foo( sub_b );
}
}
CommonLisp has multiple dispatch
(defclass a () ())
(defclass sub-a (a) ())
(defclass b () ())
(defclass sub-b (b) ())
(defgeneric foo (a b))
(defmethod foo ((x a) (y b))
(format nil "foo called on A and B~%"))
(defmethod foo ((x sub-a) (y b))
(format nil "foo called on SUB-A and B~%"))
(defmethod foo ((x a) (y sub-b))
(format nil "foo called on A and SUB-B~%"))
(defmethod foo ((x sub-a) (y sub-b))
(format nil "foo called on SUB-A and SUB-B~%"))
(defparameter *just-a* (make-instance 'a))
(defparameter *just-b* (make-instance 'b))
(defparameter *sub-a* (make-instance 'sub-a))
(defparameter *sub-b* (make-instance 'sub-b)))