TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Sushant Shinde
NA
83
1.1k
Understanding Polymorphism, inheritance in C#.
Oct 1 2018 1:33 AM
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.
Reply
Answers (
3
)
How to use Connection String in C# Language?
Sample Application on MDI form in C# Language