Let's take your example of a Dog and a Cat class, and let's illustrate using C#:
(让我们以Dog和Cat类为例,并使用C#进行说明:)
Both a dog and a cat are animals, specifically, quadruped mammals (animals are waaay too general).
(狗和猫都是动物,特别是四足动物(动物过于笼统)。)
Let us assume that you have an abstract class Mammal, for both of them: (让我们假设您有一个抽象类Mammal,这两个类都可以:)
public abstract class Mammal
This base class will probably have default methods such as:
(该基类可能具有默认方法,例如:)
All of which are behavior that have more or less the same implementation between either species.
(所有这些都是在两个物种之间或多或少具有相同实现的行为。)
To define this you will have: (要定义它,您将具有:)
public class Dog : Mammal
public class Cat : Mammal
Now let's suppose there are other mammals, which we will usually see in a zoo:
(现在,我们假设还有其他哺乳动物,我们通常会在动物园看到它们:)
public class Giraffe : Mammal
public class Rhinoceros : Mammal
public class Hippopotamus : Mammal
This will still be valid because at the core of the functionality Feed()
and Mate()
will still be the same.
(这将仍然有效,因为在功能的核心Feed()
和Mate()
仍然相同。)
However, giraffes, rhinoceros, and hippos are not exactly animals that you can make pets out of.
(但是,长颈鹿,犀牛和河马并不是可以用来饲养宠物的动物。)
That's where an interface will be useful: (这是一个有用的接口:)
public interface IPettable
{
IList<Trick> Tricks{get; set;}
void Bathe();
void Train(Trick t);
}
The implementation for the above contract will not be the same between a cat and dog;
(上述合同的执行情况在猫狗之间是不同的;)
putting their implementations in an abstract class to inherit will be a bad idea. (将其实现放在抽象类中以继承将是一个坏主意。)
Your Dog and Cat definitions should now look like:
(您的“狗”和“猫”定义现在应如下所示:)
public class Dog : Mammal, IPettable
public class Cat : Mammal, IPettable
Theoretically you can override them from a higher base class, but essentially an interface allows you to add on only the things you need into a class without the need for inheritance.
(从理论上讲,您可以从更高的基类覆盖它们,但是从本质上讲,一个接口允许您仅将需要的内容添加到类中,而无需继承。)
Consequently, because you can usually only inherit from one abstract class (in most statically typed OO languages that is... exceptions include C++) but be able to implement multiple interfaces, it allows you to construct objects in a strictly as required basis.
(因此,由于您通常只能从一个抽象类继承(在大多数静态类型的OO语言中,例外是C ++),但是能够实现多个接口,因此它允许您严格根据需要构造对象。)