Java Reference
In-Depth Information
object is passed to the equals() method of the Employee class? Since a manager is also an employee, it should
compare the two for equality. The following snippet of code shows you a possible implementation of the equals()
method for the Employee class:
// Employee.java
package com.jdojo.inheritance;
public class Employee {
private String name = "Unknown";
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean equals(Object obj) {
boolean isEqual = false;
// We compare objects of the Employee class with the objects of
// Employee class or its descendants
if (obj instanceof Employee) {
// If two have the same name, consider them equal.
Employee e = (Employee)obj;
String n = e.getName();
isEqual = n.equals(this.name);
}
return isEqual;
}
}
After you have added the equals() method to the Employee class, you can write code like the following , which
compares two objects of the Employee type for equality based on their names:
Employee emp = new Employee();
emp.setName("John Jacobs");
Manager mgr = new Manager();
mgr.setName("John Jacobs");
System.out.println(mgr.equals(emp)); // prints true
System.out.println(emp.equals(mgr)); // prints true
System.out.println(emp.equals("John Jacobs")); // prints false
In the third comparison, you compare an Employee object with a String object, which returns false . Comparing
an Employee and a Manager object returns true because they have the same names.
Search WWH ::




Custom Search