Search code examples
javaparameterspolymorphismparameter-passingvariable-types

Java polymorphism when passing variables.


class X{
    public void print(X x){System.out.println("xx");}
    public void print(Y y){System.out.println("xy");}
}
class Y extends X{
    public void print(X x){System.out.println("yx");}
    public void print(Y y){System.out.println("yy");}

    public static void main(String[] args){
        X x = new Y();
        x.print(x);
        System.out.println(x.getClass());
    }

}

The output i get is "yx" end I dont understand why, x.getClass() returns "class Y" so shouldn't its call the method where the parameter is Y?


Solution

  • Overloads (i.e. choice which of multiple methods of the same class/interface with the same name to use) are resolved based on static types. This is in opposition to overriding (choice between X#print(X) and Y#print(X) which is resolved at runtime.