'. '

# Equals

Writing equals method in OOP languages can be tricky. The Object.equals documentation suggests that the relation should be symetric but that is hard to enforce. Anyway implementation should at least try. However how should one handle (potentially unknown) subclasses? E.g. make sure instance of following class:

```class Date {
long time;

public boolean equals(Object o) {
if (o instanceof Date) {
return ((Date)o).time == time;
}
return false;
}
}```

does not return true when compared to a subclass like:

```class Interval extends Date {
int length;
}

assert !new Date(323).equals(new Interval(323, 10));```

One way to do it is to restrict the equals only to own type. E.g.:

```public boolean equals(Object o) {
if (o != null && o.getClass() == Date.class) {
return ((Date)o).time == time;
}
return false;
}
}```

This is approach suitable for algebraic types, but in OOP we might want some subclasses of Date to still be equal to plain Date instances. For example intervals of length zero may need to be equal to the Date object with the same beginning time.

#### Knowing More

Then it comes to question: Who knows more? As discussed in SuperVsInner essay in Java it is safe to assume that subclasses know more - as such it should be the subclass who handles the equals call. Here is the solution:

```class Date {
private final long time;

public Date(long time) {
this.time = time;
}

@Override
public boolean equals(Object o) {
if (o instanceof Date) {
if (o.getClass() != getClass() && getClass().isAssignableFrom(o.getClass())) {
return o.equals(this); // [1]
} else {
return time == ((Date) o).time;
}
}
return false;
}
}

class Interval extends Date {
private final int length;

public Interval(long time, int length) {
super(time);
this.length = length;
}

@Override
public boolean equals(Object o) {
if (o instanceof Interval) {
if (o.getClass() != getClass() && getClass().isAssignableFrom(o.getClass())) {
return o.equals(this); // [1]
} else {
return super.equals(o) && length == ((Interval) o).length;
}
}
return length == 0 && super.equals(o); // [2]
}
}

class SerializableDate extends Date implements java.io.Serializable {
public SerializableDate(long time) {
super(time);
}
}

assertFalse(new Date(323).equals(new Interval(323, 10)));
assertTrue(new Date(323).equals(new Interval(323, 0)));
assertTrue(new Date(323).equals(new SerializableDate(323)));```

The check [1] makes sure the comparing is always done by subclass. Then the subclass can either do nothing (like the SerializableDate) and inherits working equals from the superclass, or the subclass can use its special knowledge (like Interval at line [2]) and be equal to super class in some special conditions (here when the length is zero).