Java——运行时类型差异
我拟定了两种情况,它们之间的奇怪差异让我有点悲伤。我将尝试在下面的代码中详细说明它们。
情况一:
public void doSomething(Object obj) {
//do something with obj
}
public void doSomething(String str) {
//do something similar to str, but apply some custom
//processing for String's
}
Object o = new String("s");
doSomething(o); // this will use the Object version...
情况二:
class Dog {
void makeSound() {
System.out.println("woof");
}
}
class Chihuahua extends Dog {
void makeSound() {
System.out.println("yip");
}
}
Dog dog = new Chihuahua();
dog.makeSound(); //will print 'yip', the Chihuahua version...
为什么情况一没有使用参数的运行时类型,而情况二却使用了?我知道这些例子实际上是不同的事情,但我更好奇这里“幕后”发生了什么。
I have two situations drawn up, and the strange differences between them are causing me a bit of grief. I will attempt to detail them below in code.
Situation 1:
public void doSomething(Object obj) {
//do something with obj
}
public void doSomething(String str) {
//do something similar to str, but apply some custom
//processing for String's
}
Object o = new String("s");
doSomething(o); // this will use the Object version...
Situation 2:
class Dog {
void makeSound() {
System.out.println("woof");
}
}
class Chihuahua extends Dog {
void makeSound() {
System.out.println("yip");
}
}
Dog dog = new Chihuahua();
dog.makeSound(); //will print 'yip', the Chihuahua version...
Why, in situation one, is the runtime type of the parameter not used, but in situation two it is? I understand that the examples are actually different things, but I am more curious about what is going on 'under the covers' here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在第一个示例中,在编译时从多个重载签名中选择一个方法签名。 Java语言规范说这是基于变量的静态类型来完成的。
在第二个示例中,在运行时基于虚拟方法分派选择给定方法签名的实现。这是根据包含方法定义的类的运行时类型来完成的。
In the first example, a method signature is chosen at compile-time from among a number of overloaded signatures. The Java language specification says that this is done based on the static type of the variables.
In the second example, an implementation of a given method signature is chosen at runtime based on virtual method dispatch. This is done based on the runtime type of the class containing the method definition.
情况 #1 是方法重载,它在编译时是静态的。情况 #2 是多态性,它在运行时是动态的。
Situation #1 is method overloading, which is static at compile time. Situation #2 is polymorphism, which is dynamic at runtime.