静态分派和动态分派
Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at runtime. This is how java implements runtime polymorphism. When an overridden method is called by a reference, java determines which version of that method to execute based on the type of object it refer to. In simple words the type of object which it referred determines which version of overridden method will be called.
动态方法分派是一种在运行时解决对覆盖方法的调用的机制。 这就是java实现运行时多态的方式。 当引用调用重写的方法时,java根据其引用的对象类型确定要执行该方法的版本。 用简单的话来说,它所引用的对象类型决定了将调用哪个版本的重写方法。
用Java向上转换 (Upcasting in Java)
When Parent class reference variable refers to Child class object, it is known as Upcasting. In Java this can be done and is helpful in scenarios where multiple child classes extends one parent class. In those cases we can create a parent class reference and assign child class objects to it.
当父类引用变量引用子类对象时,称为Upcasting 。 在Java中,可以做到这一点,并且在多个子类扩展一个父类的情况下很有用。 在这些情况下,我们可以创建一个父类引用并为其分配子类对象。
Let's take an example to understand it,
让我们举个例子来了解它,
class Game
{
public void type()
{
System.out.println("Indoor & outdoor");
}
}
Class Cricket extends Game
{
public void type()
{
System.out.println("outdoor game");
}
public static void main(String[] args)
{
Game gm = new Game();
Cricket ck = new Cricket();
gm.type();
ck.type();
gm = ck; //gm refers to Cricket object
gm.type(); //calls Cricket's version of type
}
}
Indoor & outdoor Outdoor game Outdoor game
室内和室外户外游戏户外游戏
Notice the last output. This is because of the statement, gm = ck;
. Now gm.type()
will call the Cricket class version of type()
method. Because here gm
refers to the cricket object.
注意最后的输出。 这是因为语句gm = ck;
。 现在, gm.type()
将调用type()
方法的Cricket类版本。 因为这里gm
是指板球对象。
问:Java中的静态绑定和动态绑定之间的区别? (Q. Difference between Static binding and Dynamic binding in Java?)
Static binding in Java occurs during compile time while dynamic binding occurs during runtime. Static binding uses type(Class) information for binding while dynamic binding uses instance of class(Object) to resolve calling of method at run-time. Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.
Java中的静态绑定发生在编译时,而动态绑定发生在运行时。 静态绑定使用type(Class)信息进行绑定,而动态绑定使用class(Object)的实例在运行时解析方法的调用。 重载的方法使用静态绑定进行绑定,而覆盖的方法在运行时使用动态绑定进行绑定。
In simpler terms, Static binding means when the type of object which is invoking the method is determined at compile time by the compiler. While Dynamic binding means when the type of object which is invoking the method is determined at run time by the compiler.
简而言之,静态绑定是指在编译时由编译器确定调用该方法的对象的类型。 动态绑定是指在运行时由编译器确定调用该方法的对象的类型。
翻译自: https://www.studytonight.com/java/dynamic-method-dispatch.php
静态分派和动态分派