静态绑定和动态绑定 [英] Static Binding and Dynamic Binding
问题描述
我对动态绑定和静态绑定感到困惑。我已经读过,在编译时确定对象的类型称为静态绑定,在运行时确定它称为动态绑定。
以下代码中会发生什么: / p>
静态绑定或动态绑定?
这显示了什么样的多态?
class Animal
{
void eat()
{
System.out.println(动物正在吃东西);
}
}
class Dog extends Animal
{
void eat()
{
System.out.println( 狗正在吃);
}
}
public static void main(String args [])
{
Animal a = new Animal();
a.eat();
}
你的例子是动态绑定,因为在运行时确定 a
的类型是什么,并调用适当的方法。
现在假设您还有以下两种方法:
public static void callEat(Animal animal){
System.out.println(动物正在吃东西);
}
public static void callEat(狗狗){
System.out.println(狗在吃);
}
即使你改变 main
to
public static void main(String args [])
{
Animal a =新狗();
callEat(a);
}
这将打印动物正在吃
,因为对 callEat
的调用使用静态绑定,编译器只知道 a
的类型为 Animal
。
I am really confused about dynamic binding and static binding. I have read that determining the type of an object at compile time is called static binding and determining it at runtime is called dynamic binding.
What happens in the code below:
Static binding or dynamic binding?
What kind of polymorphism does this show?
class Animal
{
void eat()
{
System.out.println("Animal is eating");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("Dog is eating");
}
}
public static void main(String args[])
{
Animal a=new Animal();
a.eat();
}
Your example is dynamic binding, because at run time it is determined what the type of a
is, and the appropriate method is called.
Now assume you have the following two methods as well:
public static void callEat(Animal animal) {
System.out.println("Animal is eating");
}
public static void callEat(Dog dog) {
System.out.println("Dog is eating");
}
Even if you change your main
to
public static void main(String args[])
{
Animal a = new Dog();
callEat(a);
}
this will print Animal is eating
, because the call to callEat
uses static binding, and the compiler only knows that a
is of type Animal
.
这篇关于静态绑定和动态绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!