Java Reference
In-Depth Information
It is time to test your reimplementation of the
equals()
method in the
SmartPoint
class. Listing 7-3 is your test
class. You can observe in the output that you have two ways of comparing two
SmartPoint
objects for equality. The
equality operator (
==
) compares them based on identity and the
equals()
method compares them based on values
of the (x, y) coordinates. Note that if (x, y) coordinates are the same for two
SmartPoint
objects, the
equals()
method
returns
true
.
Listing 7-3.
A Test Class to Demonstrate the Difference Between Identity and State Comparisons
// SmartPointTest.java
package com.jdojo.object;
public class SmartPointTest {
public static void main(String[] args) {
SmartPoint pt1 = new SmartPoint(10, 10);
SmartPoint pt2 = new SmartPoint(10, 10);
SmartPoint pt3 = new SmartPoint(12, 19);
SmartPoint 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): true
pt1 == pt3: false
pt1.equals(pt3): false
pt1 == pt4: true
pt1.equals(pt4): true
There are some specifications for implementing the
equals()
method in your class, so your class will work
correctly when used with other areas (e.g. hash-based collections) of Java. It is the responsibility of the class designer
to enforce these specifications. If your class does not conform to these specifications, the Java compiler or Java
runtime will not generate any errors. Rather, objects of your class will behave incorrectly. For example, you will add
your object to a collection, but you may not be able to retrieve it. Here are specifications for the
equals()
method's
implementation. Assume that
x
,
y
, and
z
are non-null references of three objects.