Java Reference
In-Depth Information
return p.x == x && p.y == y;
}
public static void main(String[] args)
{
Point p1 = new Point(10, 20);
Point p2 = new Point(20, 30);
Point p3 = new Point(10, 20);
// Test reflexivity
System.out.println(p1.equals(p1)); // Output: true
// Test symmetry
System.out.println(p1.equals(p2)); // Output: false
System.out.println(p2.equals(p1)); // Output: false
// Test transitivity
System.out.println(p2.equals(p3)); // Output: false
System.out.println(p1.equals(p3)); // Output: true
// Test nullability
System.out.println(p1.equals(null));
//
Output:
false
// Extra test to further prove the instanceof oper-
ator's usefulness.
System.out.println(p1.equals("abc"));
//
Output:
false
}
}
the
instanceof
operatortodeterminewhethertheargumentpassedtoparameter
o
is
an instance of the
Point
class. If not, the if statement executes
return false;
.
The
o instanceof Point
expression satisfies the last portion of the contract:
Foranynonnullreferencevalue
x
,
x
.equals(null)
returnsfalse.Becausethenull
reference is not an instance of any class, passing this value to
equals()
causes the
expression to evaluate to false.
The
o instanceof Point
expression also prevents a
java.lang.ClassCastException
instance from being thrown via expression
(Point) o
in the event that you pass an object other than a
Point
object to
equals()
. (I will discuss exceptions in the next chapter.)