Saturday, July 07, 2007

Example of Polymorphism in .Net

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:

Laxmi said...

Thanks for the post

Anonymous said...

helpful for beginners

Anonymous said...

Its really a very good article which explains the concept in depth. Keep the good work going like this.

Unknown said...

Thanks for the post :)
Could you please explore thing in Depth?

Unknown said...

Really, short and sweet explanation. It's really helpful to me.

jamietownsend said...

Thanks for the easy to understand example

Anonymous said...

many many thanks it's very easy understand for beginners.

Unknown said...

Nice Work dear... Keep Writing like this

Ashish Virmani said...

thanx 4 the post...:)
nw i get to understand the diffence b/w the two types....

Manish Agrahari said...

Thanks a lot.. every post on your blog are very simple for beginners...

also visit

http://manishagrahari.blogspot.com/2011/07/polymorphism.html

sathish said...

Thanks for this article...This is very understandable...

prakash said...

ya its very usefull thanks

Rocky.. said...

Thanks..really useful..

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape