Java Reference
In-Depth Information
Sometimes you want to treat two objects as equal if they have the same state based on some or all of their
instance variables. If you want to compare two objects of your class for equality based on criteria other than their
references (identities), your class needs to reimplement the equals() method of the Object class. The default
implementation of the equals() method in the Object class compares the references of the object being passed as the
parameter and the object on which the method is called. If the two references are equal, it returns true . Otherwise,
it returns false . In other words, the equals() method in the Object class performs identity based comparison for
equality. The implementation of the method is as follows. Recall that the keyword this inside an instance method of a
class refers to the reference of the object on which the method is called.
public boolean equals(Object obj) {
return (this == obj);
}
Consider the following snippet of code. It compares some Point objects using the equality operator ( == ), which
always compares the references of its two operands. It also uses the equals() method of the Object class to compare
the same two references. The output shows that the result is the same. Note that your Point class does not contain an
equals() method. When you call the equals() method on a Point object, the equals() method's implementation of
the Object class is used.
Point pt1 = new Point(10, 10);
Point pt2 = new Point(10, 10);
Point pt3 = new Point(12, 19);
Point pt4 = pt1;
System.out.println("pt1 == pt1: " + (pt1 == pt1));
System.out.println("pt1.equals(pt1): " + pt1.equals(pt1));
System.out.println("pt1 == pt2: " + (pt1 == pt2));
System.out.println("pt1.equals(pt2): " + pt1.equals(pt2));
System.out.println("pt1 == pt3: " + (pt1 == pt3));
System.out.println("pt1.equals(pt3): " + pt1.equals(pt3));
System.out.println("pt1 == pt4: " + (pt1 == pt4));
System.out.println("pt1.equals(pt4): " + pt1.equals(pt4));
pt1 == pt1: true
pt1.equals(pt1): true
pt1 == pt2: false
pt1.equals(pt2): false
pt1 == pt3: false
pt1.equals(pt3): false
pt1 == pt4: true
pt1.equals(pt4): true
In practice, two points are considered the same if they have the same (x, y) coordinates. If you want to implement
this rule of equality for your Point class, you must reimplement the equals() method as shown in Listing 7-2.
 
Search WWH ::




Custom Search