What is the use of Java virtual method invocation?

2019-03-10 00:33发布

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条回答
萌系小妹纸
2楼-- · 2019-03-10 01:11

OK, I'll try to provide a simple example. You are writing a method that will fill a caller-supplied list:

public void fill(List l) {
  list.add("I just filled the list!");
}

Now, one caller wants to use a linked list; another one prefers a list implementation based on an array. There will be other callers with even more list implementations that you've never even heard of. These are totally different objects. Propose a solution that achieves this without relying on virtual methods.

Without virtual methods this would mean that the type List would already need to have the method add implemented. Even if you had a subtype ArrayList which had an overridden method, the compiler (and the runtime!) would simply ignore that method and use the one in List. It would be impossible to use different List implementations that conform to the same interface; it would be impossible to reuse that line of code in the method fill since it would work only with the method in the type List.

So you see, the whole idea of type hierarchy wouldn't make a lot of sense; interfaces and abstract classes couldn't even exist. The whole of Java would break down into shards without that one feature of virtual methods.

查看更多
手持菜刀,她持情操
3楼-- · 2019-03-10 01:37

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());
}

we get the result

B

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.

[EDIT to add (slightly contrived) example]
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());
  }
}

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.

查看更多
登录 后发表回答