Virtual Methods in Java

Virtual methods in Java are all non-static methods.

Virtual method invocation means that Java will look at the subclass when trying to find the right method to call.

Let’s examine an example of using virtual method invocation: Consider a method that takes an input an Animal reference and performs some operations based on the type of the animal.

 public void feedAnimal(Animal animal){
     if(animal instanceof Cow){
         ((Cow) animal).addHay();
     } else if(animal instanceof Bird){
         ((Bird) animal).addSeed();
     } else if(animal instanceof Lion){
         ((Lion) animal).addMeat();
     }
 }

In this example, you needed to know what type the animal is before applying the cast and calling the adequate method.  We can solve this issue by giving the Animal the option to feed itself, we achieve this by adding a method feed() to the abstract class Animal:

public abstract class Animal {
    public abstract void feed();
}
class Cow extends Animal{
    @Override
    public void feed() {addHay();}
    
    private void addHay(){}
}
class Bird extends Animal{
    @Override
    public void feed() {addSeed();}
    
    private void addSeed(){}
}
class Lion extends Animal{
   @Override
   public void feed() {addMeat();}
   
   private void addMeat(){}
}

The concrete Animal sub-classes have each an implementation of the feed() method. All what we need to do now is call feed() and the proper sub-class’s version will run. A better version of the feedAnimal() method would look like this:

 public void feedAnimal(Animal animal){
     animal.feed();
 }

And by this we have just applied virtual method invocation.

Leave Comment

Your email address will not be published. Required fields are marked *