Hi I’m just confused on how to to use Abstract class and Virtual. Can’t seem to find any difference between them and what are some scenarios where in it’s applicable to use abstract or virtual.
Practically speaking, there isn’t much difference. Don’t worry about it too much. I tend to use
abstract more often.
The difference has historically been quite subtle.
abtractclasses allow you to extend the class (i.e. create child classes that inherit non-private methods and variables)
virtualclass can be instantiated directly, whereas an
abstractclasses can contain
virtualmethods can have a default implementation that is inherited by child classes, whereas
abstractmethods can only be signatures, and must be implemented in child classes)
abstractclasses may contain
In practice, I haven’t seen much practical difference between the two. The
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
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
c will be available for use, along with methods
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 it’s inability to be directly constructed, is more useful to me.