What difference does the virtual class contain from the abstract class?

476    Asked by dipesh_9001 in Salesforce , Asked on May 3, 2023

 I'm just confused on how to use Abstract class and Virtual. Can't seem to find any difference between them and what are some scenarios where it's applicable to use abstract or virtual.

Answered by Ella Clarkson

The difference the virtual class can contain from the abstract class has historically been quite subtle.

Both virtual and abstract classes allow you to extend the class (i.e. create child classes that inherit non-private methods and variables)

A virtual class can be instantiated directly, whereas an abstract class cannot

Both virtual and abstract classes can contain virtual methods (virtual methods can have a default implementation that is inherited by child classes, whereas abstract methods can only be signatures, and must be implemented in child classes)

Only abstract classes may contain abstract methods

In practice, I haven't seen much practical difference between the two. The abstract and virtual modifiers, in my mind, are more important for methods (as opposed to classes).

If you're going to use a class that's either abstract or virtual, I've found that I'm more likely to be using that class as more of a contract (i.e. when you use this class, we guarantee that variables a, b, and c will be available for use, along with methods x, y, and z), rather than a specialization that is used apart, distinctly, from its parent class.

This mostly comes down to the philosophy of object-oriented design that I have learned as part of my professional career. To put it into a single sentence: If you're relying on something having a specific implementation (i.e. you need to use a square or a rectangle instead of a more general parallelogram), then you can probably improve your solution.

The general idea is that by relying on contracts rather than implementations, your code is more resistant to change. Put another way, by relying on contracts, a change to a specific implementation of that contract is contained to one or two classes (as opposed to making a change in one class ending up requiring a change to many other classes).

So for that goal (relying on a contract more than an implementation), I find myself using abstract classes more often because I tend to want the consumers of my code to use specific, specialized implementations (to suit the task at hand) rather than a general "catch-all" implementation. To that end, abstract, with its inability to be directly constructed, is more useful to me.



Your Answer

Interviews

Parent Categories