Methods

Apex Virtual Methods

Virtual Methods

Apex virtual methods allow overriding in subclasses.

What Are Virtual Methods?

Virtual methods in Apex are methods that can be overridden in derived classes. This allows developers to define a method in a base class, and then provide a specific implementation in a subclass. This feature enables polymorphism, which is a core concept of object-oriented programming.

Defining a Virtual Method in Apex

To declare a method as virtual in Apex, you use the virtual keyword. This keyword indicates that the method can be overridden by any subclass. Only methods defined within a class (not interface methods) can be declared as virtual.

Overriding a Virtual Method

To provide a specific implementation of a virtual method in a subclass, you use the override keyword. This keyword indicates that the method is intended to replace the virtual method in the parent class.

The Importance of Overriding

Overriding virtual methods allows for dynamic method invocation, making it possible to call the correct method of a subclass even when using a superclass reference. This is crucial for implementing flexible and reusable code.

For example, if you have an Animal reference that points to a Dog object, calling makeSound() will invoke the Dog's version of the method.

Best Practices with Virtual Methods

  • Use virtual methods when you have a base class and anticipate subclasses will have specific implementations.
  • Keep the base class method implementation as generic as possible.
  • Document your virtual methods to ensure other developers understand their intended use.