-1

If we look at the definition of an "interface" it describes

Interfaces allow you to specify what methods a class should implement.

Now I came across the term "what methods a class should implement" using an interface. What does it mean?

A class also has some methods defined in it, then what is the meaning of "what methods a class should implement" using an interface?

Umar Raza
  • 211
  • 1
  • 6
  • 19

2 Answers2

0

That mean that the class that implements the interface must implements all methods of the interface. But the class can have other methods.

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() { /* ... */ }
}

So, you could be sure that a class that implements ISomething have an implementation of the methods of the interface.

Syscall
  • 19,327
  • 10
  • 37
  • 52
0

what is the meaning of "what methods a class should implement" using an interface

It means that interface define common "access" to the class that implements that interface. Consider animal example:

interface IMechanicalVehicle {
    public function TurnOn();
    public function TurnOff();
}

interface IAirplane() {
    public function TakeOff();
    public function Land();
}

interface ICar {
    public function Drive();
}

Now we are having following classes:

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() {...};
}

It is because somewhere else in your code you may work on different level of abstraction. If you have a function that accepts a IMechanicalVehicle, e.g.:

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
}

... so now you can call this method with either Plane, Car or any other "thing" that implements the interface, e.g.:

Ford someFord = new Ford();
MakeMechanicalInspection(ford); // note that 'MakeMechanicalInspection' accepts IMechaniclaVehicle type as parameter, and it's fine because Ford IS A 'MakeMechanicalInspection'
Maciej Pszczolinski
  • 1,623
  • 1
  • 19
  • 38