Language:EN
Pages: 5
Rating : ⭐⭐⭐⭐⭐
Price: $10.99
Page 1 Preview
this helps ensure the symmetry test that equals

This helps ensure the symmetry test that equals

The equals Method

307

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

public class TestEquality2

5 Book III

"Martinez", "Anthony");

Chapter 6
7

Employee emp2 = new Employee(

9

else

System.out.println(

18

{

private String lastName;

308

The equals Method

42

// no object equals null

46
50
} }

Employee emp = (Employee) obj;

54

return this.lastName.equals(emp.getLastName())

55
&& this.firstName.equals(emp.getFirstName());

54

55

Returns false if the object being compared is null. This meets the last equality test: that nothing is equal to null.

Returns false if the object being compared isn’t of the correct type. This helps ensure the symmetry test: that if x equals y, y must equal x.

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

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());

The clone Method

public class CloneTest
{
public static void main(String[] args)

{

Employee emp1 = new Employee(

5
}
7
8
9

System.out.println(emp1);

10

System.out.println(emp2);

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;
}

public Object clone() {

57
60
}
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:

You are viewing 1/3rd of the document.Purchase the document to get full access instantly

Immediately available after payment
Both online and downloadable
No strings attached
How It Works
Login account
Login Your Account
Place in cart
Add to Cart
send in the money
Make payment
Document download
Download File
img

Uploaded by : Krish Ghose

PageId: ELI11BF5D3