I want to ask a question about using the equals method to test object equality in Java.
I am a beginner in Java and currently progressing through the Dummies Java 9-in-1 book.
I have written the following code to check the equality of two Employee objects:
public class TestEquality2 {
public static void main (String [] args) {
Employee emp1 = new Employee ("Martinez", "Anthony");
Employee emp2 = new Employee ("Martinez", "Anthony");
if (emp1.equals(emp2))
System.out.println("These employees are the same");
else
System.out.println("These employees are different.");
}
}
class Employee {
private String firstName;
private String lastName;
public Employee (String firstName, String lastName) {
this.lastName = lastName;
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public String getFirstName() {
return this.firstName;
}
public boolean equals (Object obj) {
// an object must equal itself
if (this == obj)
return true;
// no object equals null
if (this == null)
return false;
if (this.getClass() != obj.getClass())
return false;
// Cast to an employee, then compare the fields
Employee emp = (Employee) obj;
// is this the string's equals method?
return this.lastName.equals(emp.getLastName()) && this.firstName.equals(emp.getFirstName());
}
}
The line of concern is the last one of the equals(Object obj) method.
As per the code, I have overriden the default Object equals () method and supplied my own design, but I was confused here:
return this.lastName.equals(emp.getLastName()) && this.firstName.equals(emp.getFirstName());
I know that lastName is a string, but the equals() method that I am using here, is this the equals() method for a String or the one I've just defined? If it's the latter, I know that I would create a recursive situation, although I'm confident I am using the String equals() yet I want to clarify for completion.