Virtual vs abstract vs Interface
In the beginning of my programming journey, these three words—virtual, abstract, and interface—used to haunt me. Let's understand them today.
In Object-Oriented Programming (OOP), there is a concept called inheritance, which means using a parent class (often called the superclass) that contains some methods and properties. These can be reused in a child class (called the subclass).
✅ Virtual
Imagine a superclass named Pizza, which has a method called addPremiumToppings(). Now, I create another class GourmetPizza, which needs a similar functionality. Should I rewrite the same method again?
NO. Instead, I’ll mark the method in the superclass as virtual. In my subclass, I’ll use the extends keyword to inherit from Pizza.
If I want to change the logic, I can override the method using the override keyword. If I don’t need any changes, I can just use it as is without overriding.
So, virtual is used when I want to reuse a superclass method but still have the option to override it if needed.
✅ Abstract
Now let’s talk about abstract. If a class contains even a single abstract method, the class itself must be declared as abstract.
What does abstract mean?
It means: “Hey child class! You must implement this method.”
So, in the subclass, you must provide your own logic for every abstract method. You use the extends keyword to inherit from an abstract class.
An abstract class can also contain regular or virtual methods, which may or may not be overridden—but abstract methods are always mandatory to implement.
✅ Interface
An interface says: “You need to do this, but I won’t tell you how.”
Imagine a scenario where we need completely separate logic for each subclass, and there’s no default implementation in the parent.
Interfaces contain only method declarations—no implementation. Any class that implements an interface must use the implements keyword and define every method listed in the interface.
Example:
A pizza store offers two memberships: Gold and Silver.
You can write two separate classes for these. But what if later we add a Platinum membership? Or want to ensure that every membership class defines both delivery mode and delivery time?
In that case, we create an interface with method names like getDeliveryMode() and getDeliveryTime().
This way, we set up a rule for all future membership classes: “You must implement all these methods.”
If you understand this topic, do share in the comments that can we instantiate an interface or abstract class?