Polymorphism are essential features of C#, and We encounter these features daily. It can be a bit difficult to familiar with these features. In this post, we will explore these two features, have fun.
Inheritance enables any class (
Subclass) inherits from another (
Parent-Class), which means
Subclass will have all the members of its
Parent Class. In another word, it enables us to extend or create more specific classes from a generic base class.
TerminologyIn some books or articles, the class being inherited from is Based Class.
UML – Inheritance
The above UML diagram can be interpreted into following point:
- Parent Class – Animal
- Function 1: Eat()
- Function 2: Drink()
- Function 3: Breed()
- Child Class – Chicken
- Function 1: Cluck()
- Function 2: LayEggs()
- Child Class – Cow
- Function 1: Moo()
- Function 2: SupplyMilk
As we can image, each animal can eat, drink and breed; however, each species has its characteristic. For example, a chicken can lay eggs, but it won’t supply milk.
In the above UML diagram,
Cow inherit the character from their parent class
Animal, which includes
Code Demo – Talk Is Cheap, Show Me The Code
- Private Members of the base class (Parent Class) are not accessible from a derived class
- Public Members of the base class (Parent Class) are accessible to the derived class and external code
- Protected Members of the base class (Parent Class) are only accessible to its derived classes
- Virtual Members of the base class (Parent Class) can be overridden by the class that inherits it. This implementation doesn’t delete the original code
Polymorphism comes to the surface when we have classes that are related to each other by inheritance. From the programming perspective, polymorphism means the same function name, but multiple (different) implementations. In other words, the base class
Animal has a method called
Eat(). Child-Classes of
Animal can be dogs, birds and cats. They also have their implementation of an animal sound.
Static Polymorphism, it means the same name with multiple functions (methods can have the same name with different parameters. It is referred to as compile-time or early binding polymorphism and the decision about which method will be called is made at the compile time.
We achieve the Dynamic Polymorphism by overriding the base class method in subclass using inheritance.
In practice, we declare the method in the base class with a keyword
virtual and override the method in a subclass by using the keyword
override. In another word, the two methods use the same name and the subclass provides a new implementation.
A class with a keyword
sealed means this particular class cannot have subclass. In another word, another class can not inherit it.