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 Object
s 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.
private
andstatic
are non-virtual in Java.final
methods are non-virtual (unless they themselves override another non-final method). So while it is the normthat a method isvirtual
, it's definitely not the only option. – Mellifluousvtable
. Since this question is not about terminology, but about the concept itself, saying that Java doesn't have virtual methods would be tantamount to saying it doesn't have method dispatch. – Lacreshalacrimal