Virtual Class in Salesforce Apex

In object-oriented programming, we extend the parent class to reuse code and add new features in the child class without rewriting everything from scratch. This is what we call inheritance.

In Java, when we need to inherit from any class, we need to use the extends keyword to create the child class. However, in Salesforce Apex with the extend keyword, we must use the virtual keyword before declaring the class.

In this tutorial, we will learn about the virtual class in Salesforce Apex. In this, we will understand virtual classes and methods, why we need to use them, where they can be applied, and how to utilize them in Salesforce Apex.

Virtual Class in Salesforce Apex

A virtual class in Salesforce Apex is a class that other classes can extend, inheriting properties and methods from the parent class or super class.

In Apex, the virtual keyword enables other classes to inherit the methods and properties of the parent class. This allows users to modify or implement the functionality as needed to meet business requirements.

Additionally, normal classes, without the virtual keyword, cannot be extended or inherited into other classes.

The primary reason for using a virtual class is to create reusable code that can be easily modified or extended by other classes.

What are Virtual, Extends, and Super Keywords in Salesforce Apex?

Virtual Keyword: The virtual keyword is used to define a class or method that can be extended or overridden by child classes. A virtual method can be redefined in a subclass to provide a specific implementation while maintaining the basic structure of the original method.

Extends Keyword: The extends keyword is used to create a subclass that inherits properties and methods from a parent (or base) class. When a class extends another, it inherits the methods and variables of the parent class, allowing for code reuse and logical organization.

Super Keyword: The super keyword refers to methods and constructors of a parent class within a child class. It allows the child class to call the method or constructor from a base class, allowing the parent class’s functionality to be reused while implementing or modifying the child class.

Syntax: Using the Virtual Keyword in Salesforce Apex

We have the Apex class, and we need to extend it so that we can inherit its properties and methods in the extended class. Now, the class that we want to inherit in the extended class needs to be declared virtual.

public virtual class BaseClass {
     public void methodName() {
        //logic;
       }
}

Then, create another class extending the base class you created. You need to add the extends keyword before entering the baseclass.

public class newClass extends BaseClass {
     public void methodName1() {  
        //logic;
      }
}

Check out Apex Trigger Handler and Helper Class in Salesforce

Extended Class Without Using Virtual Class in Salesforce Apex

First, let’s determine whether we can extend or inherit from a parent class in an Apex class if we do not use the virtual keyword.

Here, I have created an Apex class named BaseClass, but I have not declared it as a virtual class.

Then, I have declared a method so that we can check after extending this class whether we can use it in the child class.

public class BaseClass {
    public void BaseMethod(){
        String Str = 'This is Base Class';
        system.debug(Str);
    }
}

After that, I created another class named ChildClass, which extends the BaseClass. Additionally, I inherited the parent class method using the super keyword, which enables us to utilize its parent class methods in the child class.

public class ChildClass Extends BaseClass {
    public void ChildMethod(){
        super.BaseMethod();
        System.debug('This is Extended Class');
    }
}

However, as you can see, we encountered an error because we did not use the virtual keyword in the parent class or the class we want to extend. Therefore, we need to declare it as a virtual class in Salesforce.

Virtual Class in Salesforce Apex

Check out How to Create and Use Constructors in Salesforce Apex Classes

How to Use Virtual Class in Salesforce Apex

Now, let’s understand how and where to utilize the virtual class in Salesforce Apex, so that we can reuse code from the parent class in the child class and add new features without rewriting everything from scratch.

Here, we created a class with a virtual keyword and method with car details, which are similar in almost every car.

However, we have not used the virtual keyword for the method that we declared in this class, even though we can use or inherit a declared method in a child class without any error.

public virtual class Car {
    public void carDetails() {
        String brand = 'TATA';
        Integer doors = 4;
        boolean isAvailable = true;
        Decimal MaxSpeed = 200;
        Decimal FuleCapacityInLTR = 40;
        
        system.debug ('Car Brand : ' +brand);
        system.debug ('Number of Doors : ' +doors );
        system.debug ('Available for rent or not : ' +isAvailable );
        system.debug ('Car Maximum Speed : ' +MaxSpeed);
        system.debug ('Car Fule Capacity : ' +FuleCapacityInLTR );
       }
}

Then, we created another class to display the information about a particular car, which was inherited from the car class using the extends keyword.

Here, we created a method in which the variable stores the car details, and then, using the super keyword, we called the carDetaild() method, which is from the base(parent) class.

That means we don’t need to write code for the information that we declared in the base class. We can call that method using the super keyword.

public class Altroz extends car{
    public void Altroz() {
        String Name = 'Altroz';
        String Color = 'Orange';
        Date Manufactured = Date.newInstance (2020,01,18);
        Decimal Price = 735000;
 
        super.carDetails();
        system.debug ('Car Name : ' +Name);
        system.debug ('Car Color : ' +Color);
        system.debug ('Car Date Manufactured : ' +Manufactured);
        system.debug ('Car Price : ' +Price);
     }
}

Similarly, create another class to display different car details. By extending the car class, we can access its methods.

public class Tiago extends car{
    public void Tiago() {
        String Name = 'Tiago';
        String Color = 'White';
        Date Manufactured = Date.newInstance(2018,09,05);
        Decimal Price = 1000000;
        
        super.carDetails();
        system.debug ('Car Name : ' +Name);
        system.debug ('Car Color : ' +Color);
        system.debug ('Car Date Manufactured : ' +Manufactured);
        system.debug ('Car Price : ' +Price);
      }
}  

In the output, you can see that even though we didn’t add the details that we added in the car class, those details are displayed in the child class because we called it the base class method using the super keyword.

Inheritance in Salesforce Apex

In this way, we can utilize virtual classes in Salesforce Apex to reuse code from the parent class in the child class, adding new features without having to code everything from scratch.

Check out How to Compare Two DateTime Values in Salesforce Apex

When We Need to Declare a Virtual Method In an Apex Class

In the above examples, we have seen that if we don’t use a virtual class, then we cannot extend that particular class, and hence we can’t inherit its methods either.

We have also seen that if we declare a class as virtual and even the method is not declared as virtual, then we can still inherit the method properties, which means it is not necessary to have methods declared as virtual.

When should we declare a method as virtual? Let’s understand this. Here I’m going to explain the virtual methods in Salesforce Apex.

When we want to override a method, the method we override must be declared as a virtual method in the parent class. Then, implement the method according to your requirements. Then, I created a map collection to store the products in the Salesforce database.

public virtual class Products {
    public virtual void updateProducts() {
        Map<Integer,String> productList = new Map<Integer,String>();
        productList.put (101,'GenWatt Diesel 1000kW');
        productList.put (102,'SLA: Bronze');
        productList.put (103,'SLA: Platinum');
        productList.put (104,'Monitor c32220');

        System.debug (' Display List of Created Products : '+productList);
    }
}

Then, create another class that extends the parent class. In this class, we can override the virtual method that we declared in the parent class. We need to add an override keyword before declaring the method.

The use of creating duplicate methods is to implement the functionality of this method rather than that of the parent class.

public class AddProducts extends Products{
    public override void updateProducts() {
        Map<Integer,String> productList = new Map<Integer,String>();
        productList.put (001,'Distance Bolt');
        productList.put (002,'Hexert Threaded Inser');
        productList.put (003,'Installation: Industrial - High');

        System.debug (' Display List of Updated Products : '+productList);
    }
}

Again, I created another class and used the same virtual method that we declared in the parent class. We can also implement the existing method’s functionality.

public class NewProducts extends Products {
    public override void updateProducts() {
        List<String> ProductList = new List<String>();
        ProductList.add ('Vaccume Cleaner');
        ProductList.add ('leaser Cutter');
        ProductList.add ('Drilling Mechines');
        ProductList.add ('Electric Generator');

        System.debug (' Display List of Updated Products : '+ProductList);
    }
}

To execute the override method, we need to create an object of the class from which we want to execute the method. You can also execute all methods and call the method using an object instance.

Overriding in Salesforce Apex

In this way, we can utilize virtual method overriding in Salesforce Apex polymorphism to implement the same method in the child class.

Conclsuion

I hope you have got an idea about the virtual class in Salesforce Apex. In that, I have explained virtual classes and methods, why we need to use them, where they can be applied, and how to utilize them in Salesforce Apex to extend the parent class to reuse code.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.