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[5]; animals[0] = new Animal(); animals[1] = new Cat(); animals[2] = new Dog(); animals[3] = new Snake(); for (int i = 0; i < 4; i++) { animals[i].Eat(); } Snake snake = new Snake(); snake.Eat(); } }
直接上代码比较容易记
运行结果。子类重写父类,实例化父类,执行子类方法,若要执行子类new出的方法,则要实例化子类。
Animal eat
Cat eat
Dog eat
Animal eat
Snake eat
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步