Example of Polymorphism in .Net
What is Polymorphism?
Polymorphism means same operation may behave differently on different classes.
Example of Compile Time Polymorphism: Method Overloading
Example of Run Time Polymorphism: Method Overriding
Example of Compile Time Polymorphism
Method Overloading
- Method with same name but with different arguments is called method overloading.
- Method Overloading forms compile-time polymorphism.
- Example of Method Overloading:
class A1
{
void hello()
{ Console.WriteLine(“Hello”); }
void hello(string s)
{ Console.WriteLine(“Hello {0}”,s); }
}
Example of Run Time Polymorphism
Method Overriding
- Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass.
- Method overriding forms Run-time polymorphism.
- Note: By default functions are not virtual in C# and so you need to write “virtual” explicitly. While by default in Java each function are virtual.
- Example of Method Overriding:
Class parent
{
virtual void hello()
{ Console.WriteLine(“Hello from Parent”); }
}
Class child : parent
{
override void hello()
{ Console.WriteLine(“Hello from Child”); }
}
static void main()
{
parent objParent = new child();
objParent.hello();
}
//Output
Hello from Child.
13 comments:
Thanks for the post
helpful for beginners
Its really a very good article which explains the concept in depth. Keep the good work going like this.
Thanks for the post :)
Could you please explore thing in Depth?
Really, short and sweet explanation. It's really helpful to me.
Thanks for the easy to understand example
many many thanks it's very easy understand for beginners.
Nice Work dear... Keep Writing like this
thanx 4 the post...:)
nw i get to understand the diffence b/w the two types....
Thanks a lot.. every post on your blog are very simple for beginners...
also visit
http://manishagrahari.blogspot.com/2011/07/polymorphism.html
Thanks for this article...This is very understandable...
ya its very usefull thanks
Thanks..really useful..
Post a Comment