Example of Polymorphism in .Net

Example of Polymorphism in .Net

 

 http://dotnetguts.blogspot.com/2007/07/example-of-polymorphism-in-net.html

Dashboards from Excel Charts and Ranges
You and your users can design dashboards, reports, charts, and models in Excel rather than hard to learn developer tools and you can easily deploy them with SpreadsheetGear for .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.

 

 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: