Search code examples
javainheritanceoverloadingdynamic-dispatchmethod-dispatch

Java 2 functions with superclass and subclass signatures - chooses superclass despite that subclass's type is subclass


I have the following code:

public class Main {

    public boolean equals(String other){
        return other == new Object();
    }

    public boolean equals(Object other){
        return other == new Object();
    }

    public static void main(String[] args){
        String s = "";
        Object b1 = new Main();
        System.out.println(b1.equals(s));

    }

}

As far as I am aware the equals method selection should work this way: During compile time the signature will be selected, and since s is of compile-time type (e.g type), the method with parameter String should be selected, and since b1 is an instance of Main then we will enter our Main implementation of equals rather than Object's.

However, when debugging I see that I enter the Main implementation with the parameter of type Object.

I saw those 2 articles:
Overloaded method selection based on the parameter's real type - doesn't explain my case, but a case in which the type of s would have been Object.

https://stackoverflow.com/a/8356435/4345843 - this answer, if true, as far as I understand supports my theory.

Would be happy for explanations.


Solution

  • This is because you assign Main instance to an Object variable. Object does not contain equals(String) method, and hence the only method that fits - equals(Object) - is chosen.