Vinoth Kumar C M
Vinoth Kumar C M

Reputation: 10598

Regarding overriding equals method in java

I tried to override equals and hashcode methods in a class. It is a subclass of another class which does not implement the equals method and hashCode methods.

Eclipse gave the below warning .

  The super class ABC does not implement equals() and hashCode() methods.
  The resulting code may not work correctly. 

Why is the above warning given ? Under what circumstances it may not work correctly ?

Upvotes: 4

Views: 719

Answers (2)

Daniel Earwicker
Daniel Earwicker

Reputation: 116654

If you say a.equals(b) versus b.equals(a) it is reasonable to expect the behaviour to be the same. But if they are of corresponding types B and A related by inheritance and only one of them properly implements equals then the behaviour will be different in those two examples.

Here, A is the superclass and does not implement equals at all (so it inherits java.lang.Object.equals). Subclass B overrides equals to depend on the name field.

class A {

  String name;

  public A() {
    this.name = "Fred";
  }

}

class B extends A {

  public boolean equals(Object o) {
    A a = (A)o;
    return a != null && a.name.equals(this.name);
  }
}

public class Test {

  public static void main(String[] args) {

    A a = new A();
    B b = new B();

    System.out.println(a.equals(b) == b.equals(a));
  }
} 

Unsurprisingly, the output is false, thus breaking symmetry.

Upvotes: 5

rahul maindargi
rahul maindargi

Reputation: 5615

Have you tried super class override the equals ... and then auto generate subclass override implementation...

I am sure it will be differnt. it will have call to super.equals()

in current auto generated implementation it is only checking values in child class..

Consider below scenario and you will understand why warning.

abstract Class A{
 private int a;
public void setA(int a){
this.a=a;
}
}

Class B extends A{
 private int x;
public void setX(int x){
this.x=x;
}

@Override
public boolean equals(Object obj) { // This does not call Super.equals
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    B other = (B) obj;
    if (x != other.x)
        return false;
    return true;
}

}

and in main Method try

B b1= new B();
b1.setA(10);
b1.setX(20);


B b2= new B();
b2.setA(20);
b2.setX(20);

if(b1.equals(b2)){
 System.out.println("Warning was Right");
}

Upvotes: 0

Related Questions