Java Reference
In-Depth Information
5.3.1 Copying objects: Cloning
To copy or clone an object to another one, we need to do it field-wise . Otherwise
we will copy only the references (as it was the case for day2=day1 ). There are
two scenarii, depending on whether the second object has already been created
(formerly using the keyword new ) or not:
Program 5.5 Cloning objects: Two scenarii
// Two Scenarii:
// Here, we assume that day2 has already been created...
day2 . dd=day1 . dd ;
day2 .mm=day1 .mm;
day2 . yyyy=day1 . yyyy ;
// day2 object has not yet been created...
static Date Copy( date day1)
{ Date newdate= new Date (day1 . dd , day1 .mm, day1 . yyyy) ;
return newdate ;
} ...
Date d2=Copy(d1) ;
Copying verbatim all records of one object to another object is also called deep
copying . Copying just their reference is shallow copying .
5.3.2 Testing for object equality
When writing programs, we often need to test for object equality. Do not use the
regular syntax == for object equality since it will only compare their references.
Of course, if references match then their fields also necessarily match. But the
general case is to have two objects created with their respective fields, for which
we would like to test for equality, field by field. Thus to physically compare
objects, we need to define and use a tailored predicate that checks the objects
field by field. For example, considering the Date objects, we may design the
following predicate:
Program 5.6
Predicate for checking whether two dates of type Date are
identical or not
static boolean isEqual(Date d1, Date d2)
return (d1.dd == d2.dd &&
d1 .mm == d2 .mm &&
d1 . yyyy== d2 . yyyy) ;
}
 
Search WWH ::




Custom Search