July 2002
Covariant Specialization Example
Here a small Java program that shows Java's static covariant method specialization. The program also demonstrates how dynamic dispatch would differ. You can download the source file here, but I imagine this page is good enough.
The most important thing to notice is that variable tempZ has the static type X, but the dynamic type Y.
Program Code
public class CovariantTest {
public static void main(String args[]) {
//FIRST WE SET UP ALL THE OBJECTS, NOTICE THE LAST IS SPECIAL
A tempA=new A();
B tempB=new B();
X tempX=new X();
Y tempY=new Y();
X tempZ=new Y(); //Dynamic dispatch test variable
System.out.println("Test dispatch on B with one variable.");
System.out.println("Last two should be the same if dynamic dispatch works.");
tempB.test(tempX);
tempB.test(tempY);
tempB.test(tempZ);
System.out.println("Test dispatch on B with two variables.");
System.out.println("The second should be identical to the first if dynamic dispatch works.");
tempB.test2(tempX, tempX);
tempB.test2(tempX, tempX);
System.out.println("---");
tempB.test2(tempX, tempY);
tempB.test2(tempX, tempZ);
System.out.println("---");
tempB.test2(tempY, tempX);
tempB.test2(tempZ, tempX);
System.out.println("---");
tempB.test2(tempY, tempY);
tempB.test2(tempZ, tempZ);
}//main
}//CovariantTest
class A{
public void test(X x){
System.out.println("A.X run");
}//test
public void test2(X a, X b){
System.out.println("A.XX run");
}//test2
}//A
class B extends A{
public void test(Y x){
System.out.println("B.Y run");
}//test
public void test2(X a, Y b){
System.out.println("B.XY run");
}//test2
public void test2(Y a, X b){
System.out.println("B.YX run");
}//test2
public void test2(Y a, Y b){
System.out.println("B.YY run");
}//test2
}//B
class X{
}//X
class Y extends X{
}//Y
Program Output
Test dispatch on B with one variable.
Last two should be the same if dynamic dispatch works.
A.X run
B.Y run
A.X run
Test dispatch on B with two variables.
The second should be identical to the first if dynamic dispatch works.
A.XX run
A.XX run
---
B.XY run
A.XX run
---
B.YX run
A.XX run
---
B.YY run
A.XX run
July 16 2002, first writing