【C#】多态

  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
上一篇:hibernate执行session.createQuery(hql)时hql若有参数则报错


下一篇:hibernate框架学习之数据查询(HQL)helloworld