As i am learning java I found that if instances of my class are comparable i should override equals() (defined in class Object
) method to determine whether two objects of my class are meaningfully equal.Probaby an attribute of the instance can be used to compare.
For a leagal override parameter passed to equals() method must be of type Object. for example.
class Moof {
private int moofValue;
Moof(int val) {
moofValue = val;
}
public int getMoofValue() {
return moofValue;
}
public boolean equals(Object o) { // Line-1
if ((o instanceof Moof) && (((Moof)o).getMoofValue()
== this.moofValue)) {
return true;
} else {
return false;
}
}
i was calling it like
Moof one = new Moof(8);
Moof two = new Moof(8);
if (one.equals(two)) {
System.out.println("one and two are equal");
}
At Line-1 if i use public boolean equals(Moof o)
it will no longer be an overriden method & becomes an overloaded method. But would it change any intended functionality? Why it is recommended to use Object
as a parameter in equals would there be any harm in using the class itself whose object is being compared?
One reason i could think is if someone calls it like one.equals((Object)two))
it would call Object's equals method instead of our equals. But why would someone call it like this?