Virtual and Override
By the end of this lesson, you'll be able to:
- Mark a parent class method as virtual to allow it to be changed
- Use override in a subclass to replace inherited behavior
- Call the parent's original version from inside an override using super
Prerequisites: "Inheritance"
Making a method changeable with virtual
public virtual class Vehicle {
public virtual String getDescription() {
return 'A generic vehicle';
}
}
public class DeliveryVan extends Vehicle {
public override String getDescription() {
return 'A delivery van';
}
}
Vehicle van = new DeliveryVan();
System.debug(van.getDescription()); // "A delivery van"
Without virtual on getDescription(), DeliveryVan would not be allowed to change it at all — Apex methods are non-overridable by default, unlike some other languages. virtual opts a method into being replaceable.
Calling the original with super
public class DeliveryVan extends Vehicle {
public override String getDescription() {
return super.getDescription() + ' (delivery configuration)';
}
}
// "A generic vehicle (delivery configuration)"
super.getDescription() calls the parent's original version from inside the override — useful when a subclass wants to add to inherited behavior rather than fully replace it.
A real business example: Construction (Equipment Tracking)
public virtual class Equipment {
public virtual Decimal getDailyRentalRate() {
return 500;
}
}
public class Crane extends Equipment {
public override Decimal getDailyRentalRate() {
return super.getDailyRentalRate() * 4; // cranes cost more
}
}
A generic daily rate exists as a sensible default on Equipment, but specific equipment types like Crane override it with their own pricing logic — while still building on the base rate rather than duplicating it.
Exercise
Given a virtual class Employee with a virtual method annualBonus() returning 1000, write a subclass Manager that overrides annualBonus() to return double the parent's value using super.
Show hint
return super.annualBonus() * 2;
Virtual and Override Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
virtual marks a method as changeable by subclasses; override replaces it with new behavior in a specific subclass — and super still gives access to the original if needed.