Java Reference
In-Depth Information
The equals() Method (continued)
}
}
public int hashcode()
{
return this.number;
}
}
Testing for a null reference is a good idea because it is a possibility. The reference
passed in is then cast to an Employee type, which is necessary because we want to treat
this object as an Employee. (Casting down the hierarchy such as this is risky, and typically
we should use instanceof to ensure that x is of type Employee. I have not discussed this
yet, though, so I have omitted it for now. The details of casting down the hierarchy tree are
discussed in Chapter 8, “Polymorphism and Abstraction.”)
Notice that the hashcode() method is also added to the Employee class. The general
rule of hash codes that should be followed is that if two objects are equal, they should gen-
erate the same hash code; therefore, classes that override the equals() method typically
need to override the hashcode() method as well.
The following statements instantiate two Employee objects and test for equality.
Employee e1 = new Employee();
Employee e2 = new Employee();
e1.number = 101;
e2.number = 102;
if(e1.equals(e2))
System.out.println(“This will not print.”);
e2.number = 101;
if(e2.equals(e1))
System.out.println(“This will print.”);
if(e1 == e2)
System.out.println(“This will not print either.”);
In the previous statements, two Employee objects are instantiated, so two equals()
methods are available to us: e1's and e2's. It does not matter if you invoke e1.equals(e2)
or e2.equals(e1), the result will be the same.
The equals() method compares two objects to see if they are equal. The = = compari-
son operator checks to see if two references point to the same object, which is an entirely
different comparison. If e1 and e2 point to different objects, the = = operator will be false,
no matter if e1 equals e2 or not.
The toString() method in the Object class is declared as public in Object;
therefore, toString() must be declared public in Radio. If a weaker access
privilege is attempted for toString() in Radio, then the Radio class will not
compile.
Search WWH ::




Custom Search