In this article we are going to see about detailed information of polymorphism, Polymorphism means many forms, There are two types of polymorphism
1. static polymorphism - decide at compile time itself
2. dynamic polymorphism - decide at runtime
Following is the class we are going to use in that,
static polymorphism :- Speech method is overload with different parameters
dynamic polymorphism :- animal class method voice is override in derived class dog, cat.
class Animal
{
public void Speech()
{
Console.WriteLine("Testing");
}
public void Speech(string
word)
{
Console.WriteLine(word);
}
public void Speech(string word, int
nooftimes)
{
for
(int i = 0; i < nooftimes; i++)
{
Console.WriteLine(word);
}
}
public virtual void Voice()
{
Console.WriteLine("No Voice");
}
}
class Dog:Animal
{
public override void Voice()
{
Console.WriteLine("Bark");
}
}
class Cat:Animal
{
public override void Voice()
{
Console.WriteLine("Meow");
}
}
static polymorphism :-
Binds the correct function to execute at the compile time itself known as early binding or static binding
public void Speech()
{
Console.WriteLine("Testing");
}
public void Speech(string word)
{
Console.WriteLine(word);
}
public void Speech(string word, int nooftimes)
{
for (int i = 0; i < nooftimes; i++)
{
Console.WriteLine(word);
}
}
operator overloading
function overloading
dynamic polymorphism :-
Binds the correct function to execute at the runtime.
public override void Voice()
{
Console.WriteLine("Bark");
}
public override void Voice()
{
Console.WriteLine("Meow");
}
Program
class Program
{
static void Main(string[] args)
{
Animal anim = new Animal();
/* Static polymorphism
*/
anim.Speech();
anim.Speech("Raj");
/* Dynamic polymorphism */
Dog d = new Dog();
Cat c = new Cat();
anim.Voice();
d.Voice();
c.Voice();
Console.Read();
}
}
class Animal
{
public void Speech()
{
Console.WriteLine("Testing");
}
public void Speech(string word)
{
Console.WriteLine(word);
}
public void Speech(string word, int
nooftimes)
{
for (int i = 0; i
< nooftimes; i++)
{
Console.WriteLine(word);
}
}
public virtual void Voice()
{
Console.WriteLine("No
Voice");
}
}
class Dog:Animal
{
public override void Voice()
{
Console.WriteLine("Bark");
}
}
class Cat:Animal
{
public override void Voice()
{
Console.WriteLine("Meow");
}
}
output
*****
Testing
Raj
No Voice
Bark
Meow
From this post you can understand about polymorphism.
No comments:
Post a Comment