This helps ensure the symmetry test that equals
The equals Method |
|
---|
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 | |
|
Chapter 6 | |
➝7 | ||
|
||
➝9 | ||
|
||
|
||
➝18 | ||
|
||
|
||
|
|
---|
➝42 |
---|
// no object equals null
➝46 |
---|
➝50 |
---|
} | } |
|
➝54 |
---|---|---|---|
|
➝55 | ||
&& this.firstName.equals(emp.getFirstName()); |
➝54 ➝55 |
|
---|
The clone Method |
---|
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:
By contrast, a clone is an altogether new object that has the same values | |
---|---|
|
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)
{ |
|
➝5 |
---|---|---|
} | ➝7 | |
➝8 | ||
➝9 | ||
|
➝10 | |
|
➝11 |
➝15 |
---|
public String getLastName()
{
return this.lastName;
}public void setLastName(String lastName) {
this.lastName = lastName;
}
The clone Method |
---|
public void setSalary(Double salary)
{
this.salary = salary;
}
|
➝57 |
---|
➝60 | |||
---|---|---|---|
} | ➝62 |
|
|
|
➝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: