The difference between virtual and abstract methods

_config.yml

I work on the 21 st floor of a building. And I’m paranoid about fire. Every now and again, somewhere in the world, a fire is burning down a sky scraper. But luckily we have an instruction manual somewhere here on what to do in case of fire:

FireEscape()

1. Don't collect belongings
2. Walk to fire escape
3. Walk out of building

This is basically a virtual method called FireEscape()

Virtual Method

This plan is pretty good for 99% of the circumstances. It’s a basic plan which works. But there is a 1% chance that the fire escape is blocked or damaged in which case you are completely screwed and you’ll become toast unless you take some drastic action. With virtual methods you can do just that: you can override the basic FireEscape() plan with your own version of the plan:

1. Run to window
2. Jump out the window
3. Parachute safely to the bottom

In other words virtual methods provide a basic plan, which can be overriden if you need to. Subclasses can override the parent class’ virtual method if the programmer deems it appropriate.

Abstract methods

Not all organisations are well drilled. Some organisations don’t do fire drills. They don’t have an overall escape policy. Every man is for himself. Management are only interested in such a policy existing.

In other words, each person is forced to develop his own FireEscape() method. One guy will walk out the fire escape. Another guy will parachute. Another guy will use rocket propulsion technology to fly away from the building. Another guy will abseil out. Management don’t care how you escape, so long as you have a basic FireEscape() plan - if they don’t you can be guaranteed OHS will come down on the organisation like a tonne of bricks.

This is what is meant by an abstract method. Sub classes are forced to implement their own FireEscape method. With a virtual method, you have a basic plan waiting for you, but can choose to implement your own if it’s not good enough.

Now that wasn’t so hard was it?

I hope it helps you

Written on November 28, 2016