DEV Community

Shreeprabha bhat
Shreeprabha bhat

Posted on

VIRTUAL FUNCTIONS IN JAVA

WHAT ARE VIRTUAL FUNCTIONS?

Virtual functions are member functions that has to be redefined in derived functions. Any function that can not be used for polymorphism can never be a virtual function. Hence a public, final or static function can never be a virtual function.

EXAMPLE:

class Animal{
void sound(){
System.out.println("All animal makes sound");
}
}
class Dog extends Animal{
void sound(){
System.out.println("Dog barks");
}
}
class Main{
public static void main(String[] args){
Animal a=new Dog();
a.sound();
}
}
Enter fullscreen mode Exit fullscreen mode

In the above example the method sound in Animal class is overridden in class Dog to provide specific implementations. In the main method the object 'a' is created using child class Dog. The method call sound() gets resolved at the runtime and the appropriate overridden method in the derived class is executed.

CONCLUSION

All non static methods are virtual functions by default in Java. Method calls on any base type are resolved at run time invoking the overridden methods in the derived classes.

Top comments (0)