There are a couple of ways you could do this. The first is to pass an
object
:
public void Hit(object x)
{
}
But this has big problems - you have to check explicitly what type teh incoming parameter is and deal with it appropriately:
public void Hit(object x)
{
Cat c = x as Cat;
if (c != null)
{
c.Run();
}
Dog d = x as Dog;
if (d != null)
{
d.Run();
}
}
That isn't a nice approach, and it's difficult to expand, and prone to errors.
The better approach would be to create a Base Class:
public abstract class Animal
{
public abstract void Run();
}
(We declare it as
abstract
so that you can't create an instance of it)
And then derive each animal class from that:
public class Dog : Animal
{
public override void Run()
{
Console.WriteLine("Dog Runs");
}
}
public class Cat : Animal
{
public override void Run()
{
Console.WriteLine("Cat Runs");
}
}
(The
override
keyword tells the system this replaces the base class version with a Cat or Dog specific version)
You can then declare your Hit method to take an Animal, and the system will sort out which Run method to use:
public class Human
{
public void Hit(Animal x)
{
x.Run();
}
}