Reputation: 1
IDE: Eclipse; Language: Java core
package p1;
public class StringTestA {
/**
* @param args
*/
public static void main(String[] args) {
Object o1 = new StringTestA();
Object o2 = new StringTestA();
StringTestA o3 = new StringTestA();
StringTestA o4 = new StringTestA();
if (o1.equals(o2)) {
System.out.println("Object o1 and o2 are eqals");
}
if (o3.equals(o4)) {
System.out.println("Object o3 and o4 are eqals");
}
}
public boolean equals(StringTestA other) {
System.out.println("StringTestA equals mathod reached");
return true;
}
}
Output:
StringTestA equals method reached
Object o3 and o4 are equals
No output if equals in not overridden.
Question: why System.out.println("Object o1 and o2 are eqals");
line is not printed as equals is returning true;
Upvotes: 0
Views: 73
Reputation: 81154
You are not overriding equals(Object)
. The argument must be an Object
, not StringTestA
. You are instead overloading equals
(creating a different method with the same name).
Always annotate methods you wish to override with @Override
. Doing so will cause a compile error if you happen to make a mistake in the method declaration, as you did here.
@Override
public boolean equals(Object obj) {
//...
}
Upvotes: 8