0

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;

1 Answer 1

8

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) { //... } 
Sign up to request clarification or add additional context in comments.

4 Comments

If you override the equals(), you MUST also override hashCode(). Otherwise a violation of the general contract for Object.hashCode will occur, which can have unexpected repercussions when your class is in conjunction with all hash-based collections.
@AndreaBorgogelliAvveduti: While this is true and good advice, it is tangential to the question. For all we know, OP did override hashCode but didn't include it because it had nothing to do with the question.
I wouldn't call it irrelevant. It is only tangentially related. I'd certainly have mentioned it as a side comment at the end of the answer, e.g., "Side note: If you're overriding equals, you have to override hashCode too." (+1, btw, good explanation, particularly re the annotation.)
@T.J.Crowder: You're right. It's a good reminder. But it belongs as a comment on the question, not an answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.