Overloading is compile-time polymorphism. Really?

后端 未结 5 1530
面向向阳花
面向向阳花 2020-12-02 17:11

I do know the syntactical difference between overriding and overloading. And I also know that overriding is run-time polymorphism and overloading is compile-time polymorphis

5条回答
  •  鱼传尺愫
    2020-12-02 18:08

    Overloaded methods can still be overridden, if that is what you ask.

    Overloaded methods are like different families, even though they share the same name. The compiler statically chooses one family given the signature, and then at run time it is dispatched to the most specific method in the class hierarchy.

    That is, method dispatching is performed in two steps:

    • The first one is done at compile time with the static information available, the compiler will emit a call for the signature that matches best your current method parameters among the list of overloaded methods in the declared type of the object the method is invoked upon.
    • The second step is performed at run time, given the method signature that should be called (previous step, remember?), the JVM will dispatch it to the most concrete overridden version in the actual type of receiver object.

    If the method arguments types are not covariant at all, overloading is equivalent to having methods names mangled at compile time; because they are effectively different methods, the JVM won't never ever dispatch them interchangeably depending on the type of the receiver.

提交回复
热议问题