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'