通过继承实现的不同对象调用相同的方法,表现出不同的行为,称之为多态
1.使用抽象类实现多态
- //抽象的Animal类,不能被实例化
- public abstract class Animal
- {
- public string Type;
- public abstract void Eat();
- }
- //小狗类继承Animal类
- public class Cat : Animal
- {
- public override void Eat()
- {
- Console.WriteLine("小猫在吃鱼!");
- }
- }
- //小猫类继承Animal类
- public class Dog : Animal
- {
- public override void Eat()
- {
- Console.WriteLine("小狗在吃骨头!");
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Animal a1 = new Cat();
- a1.Eat();
- Animal a2 = new Dog();
- a2.Eat();
- Console.ReadKey();
- }
- }
复制代码
2.使用接口实现多态
- //Animal接口
- public interface Animal
- {
- void Eat();
- }
- //小狗类继承Animal接口
- public class Cat:Animal
- {
- public void Eat()
- {
- Console.WriteLine("小猫在吃鱼!");
- }
- }
- //小猫类继承Animal接口
- public class Dog : Animal
- {
- public void Eat()
- {
- Console.WriteLine("小狗在吃骨头!");
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Animal a1 = new Cat();
- a1.Eat();
- Animal a2 = new Dog();
- a2.Eat();
- Console.ReadKey();
- }
- }
复制代码 |