Skip to content

Instantly share code, notes, and snippets.

@atomictom
Created January 25, 2015 23:28
Show Gist options
  • Select an option

  • Save atomictom/5171f97f8ffba8b3debe to your computer and use it in GitHub Desktop.

Select an option

Save atomictom/5171f97f8ffba8b3debe to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
/**
* A demonstration of the lack of multiple dispatch in Java
* Notice how there is late dispatch on the object which owns "multi"
*
* (i.e the 'c' in `c.multi(o)`)
* But there is only static dispatch on method arguments
* (i.e the 'o' in `c.multi(o)`)
*
* The output will change based on whether it's A.multi or B.multi
* but will always call the multi method defined for type X
*/
public class Generic{
public static void main(String args[]){
Generic g = new Generic();
}
public Generic(){
A a = new Generic.A();
B b = new B();
ArrayList<X> os = new ArrayList<X>();// {new Object(), new X(), new Y(), new Z()};
os.add(new X());
os.add(new Y());
os.add(new Z());
ArrayList<Multi> cs = new ArrayList<Multi>();// {new Object(), new X(), new Y(), new Z()};
cs.add(new A());
cs.add(new B());
for(Multi c: cs){
for(X o: os){
c.multi(o);
}
}
}
public interface Multi{
public void multi(Object o);
public void multi(String o);
public void multi(X o);
public void multi(Y o);
public void multi(Z o);
}
public class A implements Multi{
public void multi(Object o){
System.out.println("The first type was A");
System.out.println("The second type was Object");
}
public void multi(String o){
System.out.println("The first type was A");
System.out.println("The second type was String");
}
public void multi(X o){
System.out.println("The first type was A");
System.out.println("The second type was X");
}
public void multi(Y o){
System.out.println("The first type was A");
System.out.println("The second type was Y");
}
public void multi(Z o){
System.out.println("The first type was A");
System.out.println("The second type was Z");
}
}
public class B implements Multi{
public void multi(Object o){
System.out.println("The first type was B");
System.out.println("The second type was Object");
}
public void multi(String o){
System.out.println("The first type was B");
System.out.println("The second type was String");
}
public void multi(X o){
System.out.println("The first type was B");
System.out.println("The second type was X");
}
public void multi(Y o){
System.out.println("The first type was B");
System.out.println("The second type was Y");
}
public void multi(Z o){
System.out.println("The first type was B");
System.out.println("The second type was Z");
}
}
public class X{
}
public class Y extends X{
}
public class Z extends Y{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment