There is need to compare two objects based on class they implement? When to compare using getClass() and when getClass().getName()?
Is there any differ
Another way to achieve the same will be by overriding hashcode in subclass.
public interface Parent {
}
public static class Child1 implements Parent{
private String anyfield="child1";
@Override
public int hashCode() {
//Code based on "anyfield"
}
@Override
public boolean equals(Object obj) {
//equals based on "anyfield"
}
}
public static class Child2 implements Parent{
private String anyfield="child2";
@Override
public int hashCode() {
//Code based on "anyfield"
}
@Override
public boolean equals(Object obj) {
//equals based on "anyfield"
}
}
Now the equals will return if implementations/subclasses are of same concrete type.
public static void main(String args[]){
Parent p1=new Child1();
Parent p2=new Child1();
Parent p3=new Child2();
System.out.println("p1 and p2 are same : "+p1.equals(p2));
System.out.println("p2 and p3 are same : "+p2.equals(p3));
}
Output-
p1 and p2 are same : true
p2 and p3 are same : false