Wednesday, October 8, 2008

Polymorphism forgetfulness

Since I just got into a silly argument and lost because I retrained myself poorly I'm going to write it down several times so I can (hopefully) remember it:

Java uses the object instance to determine which overridden method to look at and the reference of a parameter to determine which overloaded method to call.

Example:

public class A {
public void test(A a) { System.out.println("A from A"); }
public void test(B b) { System.out.println("B from A"); }
}
public class B extends A {
public void test(A a) { System.out.println("A from B"); }
public void test(B b) { System.out.println("B from B"); }
}


So which class the test method is called from depends on whether you called new A() or new B(). Which method in that class is called depends on whether you assigned the object to a reference of A or B.