【问题标题】:What does it mean by implementation of methods by a class using interface? [duplicate]使用接口的类实现方法是什么意思? [复制]
【发布时间】:2021-01-01 06:29:27
【问题描述】:

如果我们看一下它所描述的“接口”的定义

接口允许你指定一个类应该实现什么方法。

现在我遇到了使用接口的术语“类应该实现哪些方法”。什么意思?

一个类也定义了一些方法,那么使用接口“一个类应该实现哪些方法”是什么意思呢?

【问题讨论】:

    标签: php oop design-patterns


    【解决方案1】:

    也就是说实现接口的类必须实现接口的所有方法。但是这个类可以有其他方法。

    interface ISomething
    {
        public function doSomething();
    }
    
    class Other implements ISomething
    {
        // SHOULD implements doSomething() to work.
        public function doSomething()
        {
        }
    
        // some methods not defined in interface
        public function doSomethingElse() { /* ... */ }
    }
    

    因此,您可以确定实现ISomething 的类具有接口方法的实现。

    【讨论】:

      【解决方案2】:

      “一个类应该实现什么方法”是什么意思? 一个接口

      这意味着接口定义了对实现该接口的类的公共“访问”。以动物为例:

      interface IMechanicalVehicle {
          public function TurnOn();
          public function TurnOff();
      }
      
      interface IAirplane() {
          public function TakeOff();
          public function Land();
      }
      
      interface ICar {
          public function Drive();
      }
      

      现在我们有以下课程:

      class Ford implements IMechanicalVehicle, ICar {
          // here you need all methods of IMechanicalVehicle and ICar
          public function TurnOn() {...};
          public function TurnOff() {...};
          public function TakeOff() {...};
          public function Land() {...};
      }
      

      这是因为您可能在代码中的其他地方处理不同的抽象级别。如果您有一个接受IMechanicalVehicle 的函数,例如:

      function MakeMechanicalInspection(IMechanicalVehicle vehicle)
      {
          vehicle.TurnOff(); // call common "access" point that every IMechanicalVehicle has, becuase interface force this method is implemented ALWAYS! otherwise code will not compile
          _inspectionService.Inspect(vehicle); // some other function
      }
      

      ...所以现在您可以使用 Plane、Car 或任何其他实现该接口的“事物”来调用此方法,例如:

      Ford someFord = new Ford();
      MakeMechanicalInspection(ford); // note that 'MakeMechanicalInspection' accepts IMechaniclaVehicle type as parameter, and it's fine because Ford IS A 'MakeMechanicalInspection'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-02
        • 1970-01-01
        • 2011-06-14
        • 1970-01-01
        • 2020-02-07
        • 2021-01-19
        相关资源
        最近更新 更多