Every class extends Object, and therefore inherits all of its methods. Two of these are particularly important and consequential in all programs, the method for testing equality:
public boolean equals (Object o)
and the method for generating a hash code:
public int hashCode ()
Equality Properties:
Reflexivity - means that an object always equals itself.
Symmetry - means that when a equals b ,b equals -a.
Transitivity - means that when a equals b and b equals c, a also equals c.
Consider a simple class that implements a two-dimensional point:
public class Point { private final int x; private final int y; public Point (int x,int y){ this.x =x;this.y =y; } public boolean equals (Object o){ if (!(o instanceof Point)) return false; Point p =(Point)o; return p.x ==x &&p.y ==y; } … }
Now suppose we add the notion of a colour:
public class ColourPoint extends Point { private Colour colour; public ColourPoint (int x,int y,Colour colour){ super (x,y); this.colour =colour; } … }
What should the equals method of ColourPoint look like? We could just inherit equals from Point, but then two ColourPoints will be deemed equal even if they have different colours. We could override it like this:
public boolean equals (Object o){ if (!(o instanceof ColourPoint)) return false; ColourPoint cp =(ColourPoint)o; return super.equals (o)&&cp.colour.equals(colour); }
This seemingly inoffensive method actually violates the requirement of symmetry. To see why, consider a point and a colour point:
Point p =new Point (1,2); ColourPoint cp =new ColourPoint (1,2,Colour.RED);
Now p.equals(cp) will return true, but cp.equals(p) will return false! The problem is that these two expressions use different equals methods: the first uses the method from Point, which ignores colour, and the second uses the method from ColourPoint.
It turns out that there is no solution to this problem: it’s a fundamental problem of inheritance. You can’t write a good equals method for ColourPoint if it inherits from Point .
However, if you implement ColourPoint using Point in its representation, so that a ColourPoint is no longer treated as a Point, the problem goes away. See Bloch’s book for details.
Copyright © 1998-2009 Dilvan Moreira