Polymorphism Using Inheritance
Explore how to apply polymorphism in C# by using inheritance and method overriding. This lesson guides you through creating base and derived classes with overridden methods to calculate product prices, illustrating key object-oriented programming principles in a real-world context.
We'll cover the following...
Let’s move a step further and implement polymorphism using the example discussed in the previous lesson.
Example
Consider the example of a Product class, which is the base class. Extending from this base class are the derived classes Beverages and Chocolates. These classes contain the GetPrice() method that calculates the selling price for the respective product.
virtual and override Keywords
We already have discussed what we need our GetPrice() method to do.
To achieve this, we need the parent class to allow the re-implementation of this inherited method. The base class allows this by using the keyword virtual in its method signature like this:
public ...