Let us look at a simple class called "Person".
class Person {
private String name;
public Person(String name) {
this.name = name;
}
public Person() {
this.name = "";
}
public boolean equals(Object o) {
System.out.println("Huh! not comparable!");
return false;
}
// This does not override java.lang.Object.equals(Object) method
// See also: Java(TM) Puzzlers: Traps, Pitfalls, and Corner Cases
// Puzzle 58 (It is easy to overload when you intend to override!)
public boolean equals(Person emp) {
return name.equals(emp.name);
}
public static void main(String[] args) {
Object e1 = new Person("Sundar");
Object e2 = new Person("Rajan");
System.out.println(e1.equals(e2));
System.out.println(e1.equals(e1));
System.out.println(e1.equals("Sundar"));
}
}
Output of the above program is as below:
Huh! not comparable! false Huh! not comparable! false Huh! not comparable! falseThis is because
equals(Object) is selected for all equals calls in the main method. If we change the main as
public static void main(String[] args) {
Person e1 = new Person("Sundar");
Person e2 = new Person("Rajan");
System.out.println(e1.equals(e2));
System.out.println(e1.equals(e1));
System.out.println(e1.equals("Sundar"));
}
We get this output:
false true Huh! not comparable! false
This is because javac's overload resolution mechanism has selected the "right" method (at the compile time) for us!
Let us check the output of the unmodified (i.e., main not changed as above) with Groovy. I'll use
jrunscript -cp ../build/groovy-engine.jar;../lib/groovy-all-1.0-JSR-06.jar -l groovy Person.java
false
true
Huh! not comparable!
false
Groovy invokes the "correct" method in all cases. This is because Groovy supports multimethods. The method actully invoked depends not only on the "receiver" - but, also on the dynamic type of the arguments. For each equals call, the correct equals method is chosen (regardless of compiled time type declared in the program).
If you want to know more about "binary methods" (single argument methods where argument type is same as that of the "receiver" - like the equals method), then you may want to refer to On Binary Methods
Posted by Bharath R on August 09, 2006 at 04:53 PM IST #
Posted by Bharath R on August 09, 2006 at 05:14 PM IST #
Posted by A. Sundararajan on August 09, 2006 at 07:46 PM IST #
Posted by Bharath R on August 10, 2006 at 12:53 PM IST #