Equality Comparison function
Suppose you want to compare two types of the Shape
class. Since Shapes
are custom classes, the compiler does not know how to compare two objects with different properties or which property to take into account. First, we need to decide what we need to compare in order to determine the equality of two Shape
objects.
Let's assert that we declare two shapes equal whenever their areas are equal. We can do this by overriding the default equals
method.
TEXT/X-JAVA
1public class Shape {
2 protected int maxWidth;
3 protected int maxHeight;
4
5 public double getArea() {
6 return getMaxArea();
7 }
8
9 @Override
10 public boolean equals(Object obj) {
11 if (obj == null)
12 return false;
13 if (obj == this)
14 return true;
15 System.out.println("Comparing");
16 return this.getArea() == ((Shape) obj).getArea();
17 }
18 // Other attributes and Methods
19}