I recently shared an article about dynamic binding and upward transformation of Java. To tell the truth, I am very lazy to read this article carefully. However, for the first program, the author explains that the parameters are matched during the compilation phase. The conclusion is that the actual call version of the overload function is determined by the compiler binding, the actual called version of the override function is determined by dynamic binding. It is still a bit reasonable, but for the program, I think it is too complicated to think about at the beginning. Paste the program first, And I modified it.
class Base{ public void foo(Base x){ System.out.println("Base.Base"); } public void foo(Derived x){ System.out.println("Base.Derived"); } } class Derived extends Base{ public void foo(Base x){ System.out.println("Derived.Base"); } public void foo(Derived x){ System.out.println("Derived.Derived"); } } public class Main{ public static void whichFoo(Base arg1, Base arg2){ arg1.foo(arg2); //System.out.println();arg2.foo(arg1); arg1.foo(arg1);arg2.foo(arg2); } public static void main(String[] args){ Base b = new Base(); Derived d = new Derived(); whichFoo(b,b); //b.foo(b);System.out.println(); whichFoo(b,d); //b.foo(d);System.out.println(); whichFoo(d,b); //d.foo(b);System.out.println(); whichFoo(d,d); //d.foo(d); } }
For the parameter in whichfoo, since the base is already given, XX is called in the function. when Foo (argx) is used, it is clear that argx is the base and will not change dynamically. You don't have to think too complicated!
If you cancel the base. Foo (Base X) function, an error is returned during compilation: you cannot apply Foo (derivide) to the base.
Therefore, the compiler determines which method to call based on the parameters to call the overloaded method. Therefore, the author summarizes that "the actual call version of the overloaded function is determined by the compiler binding, the actual called version of the override function is determined by dynamic binding. "It is easy to understand. However, the parameter transmission should not be too complicated!