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?
OK, I'll try to provide a simple example. You are writing a method that will fill a caller-supplied 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 methodadd
implemented. Even if you had a subtypeArrayList
which had an overridden method, the compiler (and the runtime!) would simply ignore that method and use the one inList
. It would be impossible to use differentList
implementations that conform to the same interface; it would be impossible to reuse that line of code in the methodfill
since it would work only with the method in the typeList
.So you see, the whole idea of type hierarchy wouldn't make a lot of sense;
interface
s andabstract class
es couldn't even exist. The whole of Java would break down into shards without that one feature of virtual methods.Here is an example. Suppose we have 2 classes:
If we now do the following:
we get the result
If Java didn't have
virtual method invocation
, it would determine at compile time that thegetName()
to be called is the one that belongs to theA
class. Since it doesn't, but determines this at runtime depending on the actual class thatmyA
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
Object
s as argument and prints them like this:This will work for any mix of Objects. If Java didn't have
virtual method invocation
, all Objects would be printed using Object´stoString()
which isn't very readable. Now instead, thetoString()
of each actual class will be used, meaning that the printout will usually be much more readable.