我们为什么需要使用接口
比如说,我定义了一个Animal父类。
现在,有3个子类。子类继承父类Animal,分别叫:Dog,Cat,Monkey
class Dog : Animal
{
public override void likeFood()
{
Console.WriteLine('我是小狗,我喜欢吃肉');
}
}
class Cat : Animal
{
public override void likeFood()
{
Console.WriteLine('我是小猫,我喜欢吃鱼');
}
}
class Monkey : Animal
{
public override void likeFood()
{
Console.WriteLine('我是猴子,我喜欢吃桃子');
}
}
有一个公园的管理员Zoo
现在,管理员Zoo想知道每个Animal喜欢的食物likeFood
管理员只需要使用zoo.show(动物),即可调用子类中重写的likeFood()函数
public static void Main(string[] args)
{
Zoo zoo = new Zoo(); //公园管理员
Dog dog = new Dog();
Cat cat = new Cat();
Monkey monkey = new Monkey();
zoo.show(dog); //'我是小狗,我喜欢吃肉'
zoo.show(cat); //'我是小狗,我喜欢吃肉'
zoo.show(monkey); //'我是猴子,我喜欢吃桃子'
}
但是问题来了
有一天,新来了一个动物:Rabbit虽然这个动物写了Rabbit类,但是他并不知道,你们之前约定的动物喜欢的食物命名为:likeFood()Rabbit类里面的方法叫:favoriteFood(),而没有像其他动物那样重写父类的方法likeFood()
class Rabbit : Animal
{
public void favoriteFood()
{
Console.WriteLine('我是兔子,我喜欢吃萝卜');
}
}
公园管理人员发现,问题在于:缺少一种约束,使得子类继承父类的时候必须实现父类的方法。
有没有一个类,能让它的子类必须实现它定义的方法?
有,那就是接口。
于是,管理人员修改Animal为接口,代码如下:
为了遵守接口命名规范,此处把之前所有的likeFood改为LikeFood首字母大写
由于Animal接口有个likeFood()方法,那么Rabbit子类去使用Animal接口的时候,必须也实现likeFood(),否则程序不能通过。这就是接口的作用。
运行结果
我是小狗,我喜欢吃肉我是小猫,我喜欢吃鱼我是猴子,我喜欢吃桃子
代码正常工作,因为Animal是接口,里面有个likeFood()方法,以后再添加各种动物进来,只需要实现Animal接口,并且也不会出现有的人会因为子类的方法命名问题而导致出错了。
虽然用继承一个普通父类也可以满足要求,但是一个普通父类根本没有约束力。
而用了接口就不一样了:子类必须实现父类的所有方法,因为Zoo类里调用的是likeFood(),由于子类必须实现父类,那么所有子类都会有likeFood(),你根本不用担心子类有没有这个方法。
接口能在多人协作下,定义一系列方法,让子类必须存在接口定义的类,防止在另外的类里调用一个人写的接口的子类时,找不到方法的问题。
完整代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
public static void Main(string[] args)
{
Zoo zoo = new Zoo();
Dog dog = new Dog();
Cat cat = new Cat();
Monkey monkey = new Monkey();
zoo.show(dog); //'我是小狗,我喜欢吃肉'
zoo.show(cat); //'我是小狗,我喜欢吃肉'
zoo.show(monkey); //'我是猴子,我喜欢吃桃子'
}
}
interface Animal
{
void LikeFood();
}
class Dog : Animal
{
public void LikeFood()
{
Console.WriteLine('我是小狗,我喜欢吃肉');
}
}
class Cat : Animal
{
public void LikeFood()
{
Console.WriteLine('我是小猫,我喜欢吃鱼');
}
}
class Monkey : Animal
{
public void LikeFood()
{
Console.WriteLine('我是猴子,我喜欢吃桃子');
}
}
class Rabbit : Animal
{
public void LikeFood()
{
Console.WriteLine('我是兔子,我喜欢吃萝卜');
}
}
class Zoo
{
public void show(Animal animal)
{
animal.LikeFood();
}
}
}
参考博文:C#接口《通俗解释》
文章为作者独立观点,不代表股票交易接口观点