Lets say I have two classes A and B . B inherits from A and B has the following methods:
public boolean equals(Object other) {
System.out.print("Object");
return true;
}
public boolean equals(A other){
System.out.print("A object");
return true;
}
public boolean equals(B other) {
System.out.print("B object");
return true;
}
A a1 = new A();
A ab = new B();
B b1 = new B();
what is unclear to me is why
ab.equals(a1)
ab.equals(b1)
Returns Object
ab is an instance of B with pointer of A. a1 is clearly both instance and pointer of A. So Why does it use the Object other instead of A other method?? same goes for b1 which is an instance of B with pointe B yet the compiler chose to apply the equals method like I inserted regular object?? AM i that stupid or is this language incoherent?
BTW A doesn't have any equals methods at all.
Explanation
But you do
And
abis:So while it is actually a
B, the variable is of typeA.Javas rules for choosing methods in such situations will start looking for an
equalsmethod in theAclass. And it actually has one, the default implementation inherited fromObject. It has the signatureSo it decides for this signature. Now it asks the actual instance behind
ab, which is of typeB, for a method with that signature. It chooses the overriden implementation inB:And consequentially prints
Objectin both cases.Details
The details for this are defined in JLS§15.12. Method Invocation Expressions. It talks about finding the most specific match. The rules can get quite complex if you dive deep into it.
Some excerpts: