Hello, I am little confused about polymorphism, inheritance in C#.
While learning about polymorphism, I found something like this ParentClass P = new ChildClass(); which is a bit confusing. Why would someone create type of parent class to store the object of child class? However it is valid in c# I just want to understand 3 things:
1. What is the purpose of doing this?
2. What are the advantages of doing this?
3. When we should create object like this?
Below is my code for reference:
- using System;
- class ParentClass
- {
- public void Display()
- {
- Console.WriteLine("Display method in Parent class");
- }
- }
- class ChildClass : ParentClass
- {
- public void Display()
- {
- Console.WriteLine("Display method in Child class");
- }
- }
- public class Program
- {
- public static void Main()
- {
- ParentClass P = new ChildClass();
- P.Display();
- }
- }
The output of the code is:
Display method in Parent class.
Now if someone has to call method in parent class why not simply create
ParentClass P = new ParentClass();
Or if someone has to call method in Child class why not simply create
ChildClass C = new ChildClass();
Have gone through lot of forums, still not found the answer I want. Please if anyone can explain in detail. It would be great. Thanks.