4. Cast obj to a variable of your class; then
compare the fields you want to base the return value
on, and return the result.
Listing 6-1: Comparing Objects
|
|
|
➝5 |
Book III |
"Martinez", "Anthony");
|
Chapter 6 |
➝7 |
Employee emp2 = new Employee(
|
|
➝9 |
|
|
|
else
|
System.out.println(
|
|
|
|
➝18 |
|
|
|
{
|
private String lastName;
|
|
// no object equals null
return this.lastName.equals(emp.getLastName())
|
➝55 |
Cloning refers to the process of making an exact duplicate
of an object.
Unfortunately, this process turns out to be a pretty difficult task
in an object-oriented language such as Java. You’d think that cloning
would be as easy as this:
as the original object. Often you can create a clone manually by
using code like this:
|
Book III Chapter 6 |
Employee emp1 = new Employee("Stewart", "Martha"); Employee emp2 =
new Employee();
emp2.setLastName(emp1.getLastName());
emp2.setFirstName(emp1.getFirstName());
emp2.setSalary(emp1.getSalary());
public class CloneTest
{
public static void main(String[] args)
} |
|
➝7 |
|
|
➝8 |
|
➝9 |
System.out.println(emp1);
|
➝10 |
System.out.println(emp2);
|
➝11 |
public String getLastName()
{
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setSalary(Double salary)
{
this.salary = salary;
}
|
} |
|
➝62 |
Book III
|
return emp;
|
➝63 |
|
As you can see, the name of the second Employee object was
successfully changed without affecting the name of the first Employee
object.
The following paragraphs draw your attention to some of the
highlights of this program: