虚方法和重写
这是一个父类:
class Animal
{
public virtual void Eat()
{
Console.WriteLine("动物在吃饭");
}
}
这是子类猫,重写父类虚方法
class Cat:Animal
{
public override void Eat()
{
Console.WriteLine("猫在吃鱼");
}
}
这是子类狗,重写父类虚方法
class Dog:Animal
{
public override void Eat()
{
Console.WriteLine("狗在吃骨头");
}
}
主程测试:
static void Main(string[] args)
{
Animal[] animals = new Animal[5];
//向上转型
animals[0] = new Dog();
animals[1] = new Dog();
animals[2] = new Cat();
animals[3] = new Cat();
animals[4] = new Dog();
for (int i = 0; i < animals.Length; i++)
{
if (animals[i] is Dog)
{
//向下转型
((Dog)animals[i]).Eat();
}
else
{
((Cat)animals[i]).Eat();
}
animals[i].Eat();
}
//重写和重载有什么区别?
/*
* 相同:
* 重载和重写的方法名都一致
*
* 不同点:
* 重写是在父子类中的 重载是在同一个类中
* 重写的参数列表一致 重载的参数列表不同
* 重写是运行时多态 重载是编译时多态
*
*/
}