Where did the concept of Interfaces come from?

后端 未结 18 2269
有刺的猬
有刺的猬 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:34

    Interfaces came from computer science. Or, let's say, from common sense in programming. Interface is a logical group of methods of a class. C++ didn't need a separate language concept of "interface", because any class might be used as an interface -- just define a set of methods in it, make no implementation, call it like IExecutable and use:

    class IExecutable
    {
    public:
        virtual void Execute() = 0;
    };
    
    class MyClass : public IExecutable
    {
    public:
        void Execute() { return; };
    };
    

    Some languages, called "dynamically typed", like Python, don't require to define interfaces at all, you just call a method you need, and run-time checks if it is possible ("If it walks like a duck and talks like a duck, it must be a duck").

    C# clearly separates a concept of interfaces from classes, because it uses static typing... and multiple inheritance is prohibited in that language, but it is ok for a class to have one base class and another interface, or to implement several interfaces at a time.

    public interface IPurring
    {
        void Purr();
    }
    
    public class Cat : Animal, IPurring
    {
        public Cat(bool _isAlive)
        {
            isAlive = _isAlive;
        }
    
        #region IPurring Members
    
        public void Purr()
        {
            //implement purring
        }
    
        #endregion
    }
    

提交回复
热议问题