Java Reference
In-Depth Information
public String toString()
{
System.out.println(“Inside Radio toString”);
String rep = “Radio volume = “ + volume + “, channel = “
+ channel + “ and band = “ + band;
return rep;
}
}
The equals() Method
The Object class has an equals() method for determining whether two objects are equal.
The idea is that every class you write will override the equals() method, allowing users of
your class to determine when instances are equal.
What does it mean for two Employee objects to be equal? You get to decide. For exam-
ple, maybe two employees are equal if they work in the same department, or have the
same manager, or get paid the same amount. More likely, suppose that two employees are
the same if they have the same number. Whatever logic you decide on, you perform that
logic by overriding equals() in the Employee class.
The following Employee class overrides equals() and determines that two objects are
equal if they have the same number.
public class Employee
{
public String name;
public String address;
public int SSN;
public int number;
public void mailCheck()
{
System.out.println(“Mailing a check to “ + name
+ “ “ + address);
}
public boolean equals(Object x)
{
if(x == null)
return false;
Employee other = (Employee) x;
if(this.number == other.number)
{
return true;
}
else
{
return false;
continued
Search WWH ::




Custom Search