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; interface
s and abstract class
es couldn't even exist. The whole of Java would break down into shards without that one feature of virtual methods.