public class Animal
{
public virtual void Eat()
{
Console.WriteLine("Animal eat");
Console.ReadKey();
}
} public class Cat : Animal
{
public override void Eat()
{
Console.WriteLine("Cat eat");
Console.ReadKey();
}
} public class Dog : Animal
{
public override void Eat()
{
Console.WriteLine("Dog eat");
Console.ReadKey();
}
}
public class Snake : Animal
{
public new void Eat()
{
Console.WriteLine("Snake eat");
Console.ReadKey();
}
} class Tester
{
static void Main(string[] args)
{
Animal[] animals = new Animal[]; animals[] = new Animal();
animals[] = new Cat();
animals[] = new Dog();
animals[] = new Snake();
for (int i = ; i < ; i++)
{
animals[i].Eat();
}
Snake snake = new Snake();
snake.Eat();
}
}
直接上代码比较容易记
运行结果。子类重写父类,实例化父类,执行子类方法,若要执行子类new出的方法,则要实例化子类。
Animal eat
Cat eat
Dog eat
Animal eat
Snake eat