They are kind of like class templates. An interface is more like a contract though, while an abstract class is similar to an interface but also includes some common functionality to be passed into an implementation.
An interface is used to guarantee that a particular class has methods that take specific arguments and/or return something consistent while encapsulating what goes on.
Here is a simple example.
This is bad because every time you want to add a new type of food you have to modify the dinner class. The classes are not loosely coupled meaning a change to one class requires changes to another.
Code: Select all
class taco
{
function fold() { ..stuff..}
}
class burrito
{
function roll() { ..stuff.. }
}
class dinner()
{
function make( object $food )
{
if( $food instanceof burrito )
$food->roll() ;
if( $food instanceof taco )
$food->fold() ;
$this->serve($food) ;
}
}
This is good. Now we are programming to an interface. Dinner doesn't care what is passed to it as long as it implements the food contract. Now if you add a new type of food you don't have to bother editing the dinner class.
Code: Select all
interface food
{
function prepare() ;
}
class taco implements food
{
function prepare() { ..stuff..}
}
class burrito implements food
{
function prepare() { ..stuff.. }
}
class dinner()
{
function make( food $food )
{
$food->prepare() ;
$this->serve($food)
}
}