Write a program that implements dynamic polymorphism.

 Posted by Nagasundar_Tn on 11/14/2012 | Category: C# Interview questions | Views: 4090 | Points: 40
Answer:

namespace DynamicPolymorphism

{
public abstract class Animal
{
public abstract void Run();
}

public class Tiger : Animal
{
public override void Run()
{
Console.WriteLine("Tiger runs at 80 Km/hr");
}
}

public class Lion : Animal
{
public override void Run()
{
Console.WriteLine("Lion runs at 60 Km/hr");
}

}

class Program
{
static void Main(string[] args)
{
Animal objAnimal = new Lion();
objAnimal.Run();
objAnimal = new Tiger();
objAnimal.Run();
Console.Read();
}
}
}


Here i have a abstract class called Animal. This Animal class contains an abstract method called Run(). Note that here method declaration is only written and not implementation.
Now I have two classes called Tiger and Lion. These two classes inherits from base class Animal.
  public class Lion : Animal

public class Tiger : Animal

I override the base class Run() method in my Lion and Tiger class.
The keyword override is used to override the base class function.
public override void Run() ---> in Tiger and Lion class overrides the base class Run() function.

I am printing in Lion class
 Console.WriteLine("Lion runs at 60 Km/hr");

I am printing in Tiger class
 Console.WriteLine("Tiger runs at 80 Km/hr");

In program class the real implementation is done.
At first I am creating base class reference pointing to derived class.
In first line I am creating Animal class reference pointing to Lion class using "new" keyword
Animal objAnimal = new Lion();
Then I am calling Run() function, now it calls the Run() function of Lion class and executes the line
 Console.WriteLine("Lion runs at 60 Km/hr"); 

Now I am reassigining or changing the reference from Lion class to Tiger class . Note that I am using the same object "objAnimal"
 objAnimal = new Tiger();   
Then I am calling Run() function, now it calls the Run() function of Tiger class and executes the line
 Console.WriteLine("Lion runs at 60 Km/hr"); 


Asked In: In my last interview | Alert Moderator 

Comments or Responses

Login to post response