Java Reference
In-Depth Information
provides several null-safe or null-tolerant class methods for comparing two objects,
computingthehashcodeofanobject,requiringthatareferencenotbenull,andreturn-
ing a string representation of an object.
Cloning
The
clone()
method
clones
(duplicates) an object without calling a constructor. It
copies each primitive or reference field's value to its counterpart in the clone, a task
known as
shallow copying
or
shallow cloning
.
Listing 2-25
demonstrates this behavior.
Listing 2-25.
Shallowly cloning an
Employee
object
class Employee implements Cloneable
{
String name;
int age;
Employee(String name, int age)
{
this.name = name;
this.age = age;
}
public
static
void
main(String[]
args)
throws
CloneNotSupportedException
{
Employee e1 = new Employee("John Doe", 46);
Employee e2 = (Employee) e1.clone();
System.out.println(e1 == e2); // Output: false
System.out.println(e1.name == e2.name); // Output:
true
}
}
aconstructorforinitializingthesefields.The
main()
methodusesthisconstructorto
initialize a new
Employee
object's copies of these fields to
John Doe
and
46
.