Where did the concept of Interfaces come from?

后端 未结 18 2113
有刺的猬
有刺的猬 2021-01-11 18:45

In c#, we have interfaces. Where did these come from? They didn\'t exist in c++.

18条回答
  •  暖寄归人
    2021-01-11 19:31

    They came from java, and they were introduced because java (and C#) do not allow multiple inheritance.

    EDIT: I'm receiving some downmods because people using COM interfaces in C++ disagree with the above statement. Regardless, the concept of an interface came from java, C++ COM interfaces were virtual classes, java was the first language to make it a language feature.

    END EDIT

    For example, in C++, you could have a class named Dog that inherited from Animal and Mammal.

    In C#, you would have a base class named Animal, and use an interface (IMammal). The I naming notation is historical from C++ (It was used to indicate an abstract virtual class), and was carried over to java but is more significant in C#, because there is no easy way to tell what is a base class and what is a interface from a C# class declaration:

    public class Dog : Animal, IMammal
    

    while in Java it was more obvious:

    public class Dog extends Animal implements IMammal
    

    Multiple inheritance is very tricky, so interfaces were derived to simplify it. A C# class can only inherit from one base class, but can implement N amount of interfaces.

    In C++, interfaces can be simulated by using pure virtual classes. These require all methods to be overridden polymorphicaly by the inheriting class.

提交回复
热议问题