Flipkart Interview Question
Software Engineer / DevelopersYes. This is what was expected by interviewer. He wanted to focus on the fact that we should use classname comparison instead of instanceof comparison while comparing objects in equals.
Assuming you meant
Student s2 = new Student2("firstName", "lastName", 23 true);
s1.equals(s2) will return true. Generally speaking, if some value, in this case, last name, is part of the identity of an object, it should not be added via inheritance.
import java.lang.*;
public class TestEquals {
static class Student {
protected String firstName;
Student(String aFirstName) {
firstName = aFirstName;
}
public String getFirstName() {
return firstName;
}
public boolean equals(Student s) {
return firstName.equals(s.getFirstName());
}
}
static class Student2 extends Student {
protected String lastName;
Student2(String aFirstName, String aLastName) {
super(aFirstName);
lastName = aLastName;
}
}
public static void main(String args[]) {
System.out.println("Testing equals...");
Student s1 = new Student("First");
Student s2 = new Student2("First", "Last");
if (s1.equals(s2)) {
System.out.println("Students are equal");
} else {
System.out.println("Students are not equal");
}
}
}
The correct implementation should be resulting as follows I guess....
if s1.equals(s2) is asked it should return true
Since all the fields in s1 are there in s2
but at the same time
if s2.equals(s1) is asked it should return false.
Since s2 has an extra field "LastName"
No.. Objects of two different class should never be equal though their fields can be equal.
s1.equals(s2)
calls the equals method of the super class
s2.equals(s1)
also calls equals method of the super class
thus both return true
Ideally equals implementation for Student should be like this
public boolean equals( Student a) {
if(this.getClass().getName().equals(a.getClass().getName())) {
if(this.firstname.equals(a.firstname)) {
if(this.isboy == a.isboy) {
if(this.age == a.age) {
return true;
}
}
}
}
return false;
}
then for both the above statements it will return false
If it uses default implementation of equals() method, it will return false. Verified on a compiler.
Good implementation of equals method should have o.getClass().getName().equals(this.getClass().getName())
- Vitaly.Arbuzov January 27, 2011equals should be reflexive, symmetric and transitive.
In case you add property to Student2 you'll break symmetric of relation so that student2.equals(student1) will be false and student1.equals(student2) will be true;