The programmers coming from c++ background to Java normally think that where is the Virtual function? In Java there is no keyword names “virtual“.
Definition of Virtual from wiki:
In object-oriented programming, a virtual function or virtual method is a function or method whose behaviour can be overridden within an inheriting class by a function with the same signature to provide the polymorphic behavior.
Therefore according to definition, every non-static method in JAVA is by default virtual method except final and private methods. The methods which cannot be inherited for polymorphic behavior is not a virtual method.
import java.util.*; public class Animal { public void eat() { System.out.println("I eat like a generic Animal."); } public static void main(String[] args) { List<Animal> animals = new LinkedList<Animal>(); animals.add(new Animal()); animals.add(new Wolf()); animals.add(new Fish()); animals.add(new Goldfish()); animals.add(new OtherAnimal()); for (Animal currentAnimal : animals) { currentAnimal.eat(); } } } public class Wolf extends Animal { @Override public void eat() { System.out.println("I eat like a wolf!"); } } public class Fish extends Animal { @Override public void eat() { System.out.println("I eat like a fish!"); } } public class Goldfish extends Fish { @Override public void eat() { System.out.println("I eat like a goldfish!"); } } public class OtherAnimal extends Animal {}
Output:
I eat like a generic Animal.
I eat like a wolf!
I eat like a fish!
I eat like a goldfish!
I eat like a generic Animal.
Abstract class is nothing but the pure virtual method equivalent to C++ in Java.
Question : why we say that static method is not a virtual method in Java?
Answer : static method is bound to the class itself, so calling the static method from class name or object does not provide the polymorphic behavior to the static method. We can override the static method however it will not give the advantage of the polymorphism.
Leave a Reply