Pop*_*oko 17 java methods runtime
我在一些计算机科学测试中看到了下一段,我希望我能在这里得到一个很好的解释,因为我用谷歌搜索了一个小时,找不到任何东西.
"当我们说Java语言有虚方法调用时,我们的意思是在java应用程序中,执行的方法由运行时的对象类型决定"
这是什么意思?谁能更好地解释一下?
ami*_*mit 33
这些行的作者使用了c ++术语virtual.
更好的术语是动态绑定/动态分派.
这意味着,对象的动态类型是"选择"将调用哪个方法,而不是静态类型.
例如:[伪代码]:
class A {
public void foo() { }
}
class B extends A {
public void foo() { }
}
Run Code Online (Sandbox Code Playgroud)
在调用时:
A obj = new B();
obj.foo();
Run Code Online (Sandbox Code Playgroud)
B.foo()将被调用,而不是A.foo(),因为动态类型obj是B.
Jig*_*shi 13
我们的意思是在java应用程序中,执行的方法由运行时的对象类型决定
interface Animal{
public void eat();
}
class Person implements Animal{
public void eat(){ System.out.println("Eating Food");}
}
class Eagle implements Animal{
public void eat(){ System.out.println("Eating Snake");}
}
Run Code Online (Sandbox Code Playgroud)
在主要
Animal animal = new Person();
animal.eat(); //it will print eating food
animal = new Eagle();
animal.eat(); //it will print eating snake
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33847 次 |
| 最近记录: |