0

This is the way we implement equals method in classes.

Class A (Store) with area as instance variable:

@Override
public boolean equals(Object otherObject) {
    if (this == otherObject) {
        return true;
    }
    if (otherObject == null || getClass() != otherObject.getClass()) {
        return false;
    }

    Store otherStore = (Store) otherObject;

    return area == otherStore.area; 
}

Class B (StoreToys) extends Class A (Store) and has no instance variables (dealing with inheritance)

How should i write equals method for this class?

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
John
  • 1
  • 1
  • 1
    `getClass() != otherObject.getClass()` why are you doing this instead of `instanceof`? `getClass` is something that Effective Java explicitly warns you not to do because it breaks the Liskov Substitution Principle. – Powerlord Apr 19 '18 at 22:15
  • Possible duplicate of [Java - equals method in base class and in subclasses](https://stackoverflow.com/questions/13162188/java-equals-method-in-base-class-and-in-subclasses) – Bartosz Bilicki Apr 19 '18 at 22:23

1 Answers1

0

If you don't introduce any new fields in StoreToys you can write the check with instanceof to verify that otherObject can be cast to Store.

@Override
public boolean equals(Object otherObject) {
  if (this == otherObject) {
    return true;
  }
  if (!(otherObject instanceof Store)) {
    return false;
  }
  Store otherStore = (Store) otherObject;
  return area == otherStore.area; 
}
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111