virtual function in java,example
In Java, the concept of a "virtual function" is implemented through the use of method overriding in inheritance. In Java, all non-static methods are virtual by default, meaning that the method that gets executed is determined at runtime based on the object's actual class, not the reference type.
Here's a simple example to illustrate how virtual functions work in Java:
// Base class
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
// Derived class 1
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
// Derived class 2
class Cat extends Animal {
@Override
void sound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
// Creating objects of the derived classes
Animal myDog = new Dog();
Animal myCat = new Cat();
// Calling the overridden method
myDog.sound(); // Output: Dog barks
myCat.sound(); // Output: Cat meows
}
}
Base Class (Animal
): This class has a method sound()
that prints a generic message.
Derived Classes (Dog
and Cat
): Both classes extend Animal
and override the sound()
method to provide specific implementations.
Main Class: In the main
method, we create references of type Animal
but instantiate them with Dog
and Cat
objects. When we call the sound()
method on these references, the overridden methods in the respective classes are executed.