0
public class Test5 {
    public static void main(String... args){
        C o1 = new D();             
        o1.m(1.0,1.0);      
        o1.m(1.0f, 1.0f);   
    }
}

class C{
   
    public void m(double x, double y) {
        System.out.println("C' m(double,double)");
    }
}

class D extends C{
    public void m(float x, float y) {
        System.out.println("D's m(float,float)");
    }
}

why the output is

C' m(double,double)

C' m(double,double)

for o1.m(1.0f, 1.0f); I think it will call public void m(float x, float y) in class D, I don't understand why it is determined by the declaration type instead of reference type

  • 1
    Java doesn't have [multiple dispatch](https://en.wikipedia.org/wiki/Multiple_dispatch). Which method signature to call is determined at compile-time. Java sees that o1 is a C. C only has a method for doubles. Floats are compatible with that, since they can be widened, so the double version is chosen. This choice forms part of the bytecode. The fact that there is a more specific signature at runtime doesn't factor into it. – Michael Apr 14 '21 at 14:46
  • @Michael thanks for your reply, and it's really helpful! – zippermonkey Apr 14 '21 at 15:07

0 Answers0