View this PageEdit this Page (locked)Attachments to this PageHistory of this PageHomeRecent ChangesSearch the SwikiHelp Guide

Ricardo Wardhana: "Identity, Equality and Equivalence"

Ricardo Wardhana
gtg651m


Identity, Equality and Equivalence



Most people do not give distinction between the name of the object and the thing that the object represents. However, in Object Oriented programming those distinctions are very important. Thus we have to be careful in the way we consider under what circumstances two distinct objects are equal.

In java the equality operator “==” is used to determine whether 2 objects are identically equal. Say, in the example below, it only check whether ‘p’ and ‘q’ refer to the same object BUT it does not check whether they contain the same data. Look at the example below.


Point p = new Point (2,3);
Point q = p; // q is IDENTICALLY EQUAL to p
Boolean ideq = (q == p); // return true as there is only one point object


In contrast:


Point p = new Point (2,3);
Point q = new Point(p); // q is EQUAL to p
Boolean ideq = (q == p); // return false as there are two distinct Point object


By now you should have seen that the “==” (equality operator) is not quite that useful in comparing objects. It only determines whether their REFERNCES are the same or different.

Now, let us talk about the “equals()” method. The “equals()” method can be defined to determine equality between objects in any way we consider appropriate. For example:


;; we consider that 2 apples are equal if they have the same weight and name

public class Apple
{
	private String name;
	private String taste;
	private int weight;

	// accessors and modifiers

	public Boolean equals(Object o)
	{
		if(o instance of apple) // check whether o is an instance of apple
		{
			Apple p = (apple) o; // cast o as an apple and assign it to p
			return (this.weight == p.getWeight() & this.name.equals(p.getName()));
							}
		return false;
	}
}




=================================================================
Thus the Golden Rule is:
=================================================================



A few things to note:



Hope this helps.


All materials are courtesy of Java Software Solution, Schaum's Outlines (programming with java), and materials taught in class and review sessions.






Links to this Page