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) {
System.out.println('o');
}
void print(ArrayList l, Set s) {
System.out.println('s');
}
}

发表评论

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

WordPress.com 徽标

您正在使用您的 WordPress.com 账号评论。 登出 /  更改 )

Google photo

您正在使用您的 Google 账号评论。 登出 /  更改 )

Twitter picture

您正在使用您的 Twitter 账号评论。 登出 /  更改 )

Facebook photo

您正在使用您的 Facebook 账号评论。 登出 /  更改 )

Connecting to %s