Next page | Contents page |

Copying and comparing objects

Copying objects

We have seen that if you assign a class-type variable to another one you will only copy the reference, so both variables then refer to the same object:

	Rectangle r = new Rectangle (3, 2);
	Rectangle q = r;

What if you really do want to duplicate the object, not just the reference?

At this stage all we can do is to make you aware that every object potentially has a method called clone (). To use it, its details must be written for each class. How to do that will be shown later.

However, arrays can always be cloned:

	int [][] table = {{1, 2, 3}, {4, 5, 6}};
	int [][] copy = (int [][]) table.clone ();
	               // The cast to the array type is necessary: we will see why soon

Comparing objects

Similarly, testing two class-type variables for equality, using == or != will only compare the references: do the variables refer to the same object?

Again, we point out here that every object potentially has method equals (), testing whether 2 distinct objects are identical because they are of the same class and the values of all their fields are the same. The method returns a boolean. But the details of the method have to be written for each class and we have not yet covered enough to show how that is done.

Next page | Contents page |