Java虚拟方法调用有什么用? [英] What is the use of Java virtual method invocation?

查看:104
本文介绍了Java虚拟方法调用有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解什么是Java方法调用,并已使用该方法练习了许多示例.

I understand what is java method invocation and have practiced many examples using it.

我想知道这个概念的实际情况或需要. 如果任何人都可以给出使用它的真实场景并为之提供帮助,那将有很大的帮助. 如果没有这个概念,会发生什么?

I want to know what is the practical situation or need of this concept. It would be of great help if anyone could give a real world scenario where it is used and what would happen if this concept would have not been there?

推荐答案

这里是一个示例.假设我们有2个类:

Here is an example. Suppose we have 2 classes:

class A {
    public String getName() {
        return "A";
    }
}

class B extends A {
    public String getName() {
        return "B";
    }
}

如果我们现在执行以下操作:

If we now do the following:

public static void main(String[] args) {
    A myA = new B();
    System.out.println(myA.getName());
}

我们得到结果

B

如果Java没有virtual method invocation,它将在编译时确定要调用的getName()是属于A类的那个.既然不是,而是根据myA指向的实际类在运行时确定,我们得到上面的结果.

If Java didn't have virtual method invocation, it would determine at compile time that the getName() to be called is the one that belongs to the A class. Since it doesn't, but determines this at runtime depending on the actual class that myA points to, we get the above result.


您可以使用此功能编写一种方法,该方法将任意数量的Object作为参数并按如下所示打印它们:


You could use this feature to write a method that takes any number of Objects as argument and prints them like this:

public void printObjects(Object... objects) {
  for (Object o: objects) {
    System.out.println(o.toString());
  }
}

这将适用于任何对象混合.如果Java没有virtual method invocation,则将使用不太可读的Object's toString()打印所有对象.现在改为使用每个实际类的toString(),这意味着打印输出通常更易读.

This will work for any mix of Objects. If Java didn't have virtual method invocation, all Objects would be printed using Object´s toString() which isn't very readable. Now instead, the toString() of each actual class will be used, meaning that the printout will usually be much more readable.

这篇关于Java虚拟方法调用有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆