Java——运行时类型差异

发布于 2024-11-07 07:56:05 字数 723 浏览 1 评论 0原文

我拟定了两种情况,它们之间的奇怪差异让我有点悲伤。我将尝试在下面的代码中详细说明它们。

情况一:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

国粹 2024-11-14 07:56:05

在第一个示例中,在编译时从多个重载签名中选择一个方法签名。 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.

别把无礼当个性 2024-11-14 07:56:05

情况 #1 是方法重载,它在编译时是静态的。情况 #2 是多态性,它在运行时是动态的。

Situation #1 is method overloading, which is static at compile time. Situation #2 is polymorphism, which is dynamic at runtime.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文