overloaded method call resolution — static binding

class Visitor{ // visitor pattern, overloading
void visit(Object o){…} //1
void visit(String s){…} //2

If you call
Object o = makeAnObjectOrString(); aVisitor.visit(o), which method runs? I felt it’s resolved at run time. Wrong.

Interviewer pointed out equals(Object o). A novice creates an equals(MyClass o){…}, overloading the inherited equals(Object o). When MyClass is used in an ArrayList, the new method will never be called, because ArrayList.java (see source code) always casts any MyClass instance to Object and calls equals(Object o).

[[Java Precisely]] P44 suggests (1) will be chosen, and always at compile time. At compile time, (2) is ruled out.

public class JavaPreciselyP44 {
static JavaPreciselyP44 instance = new JavaPreciselyP44();
public static void main(String argsp[]) {
//method call won't compile since both methods are equally applicable
instance.print(new ArrayList(), new HashSet());
void print(List l, HashSet s) {
void print(ArrayList l, Set s) {

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s