How do I compare Base class object with derived class object in derived class? I need to get true as output from the code below:
class Base {
int i;
String str;
}
class Derived extends Base{
double d;
String str1;
public static void main(String []a){
Base b= new Base();
Derived d = new Derived();
System.out.println("Equals! :"+d.equals(b));
}
}
It always gives me false as output. How can I compare base class with derived class?
Object equality is usually defined for objects of the same class, e.g.: You might want two objects
Base b1, b2to be equal if theirstrandivalues are equal. Then you would need to define theequals()(and, typically,hashCode()) methods to test for this condition. For example:In your case, since
BaseandDerivedare different classes, with different attributes (Basehasstrandi, whileDerivedhasstr,i,str1, andd), you would need to define exactly when are aBaseobject and aDerivedobject supposed to be equal.