Interface vs abstract class

Hello,
I’ve just started playing with OOP in PHP and wonder: what’s the conceptual difference between interface (which may be implemented in a class) and abstract class (which may be inherited by the same class) ?

I’ll be very grateful if you show some examples pointing difference in a clear way

Thank you

the abstract class enables you to have common functionality coded there as the interface is only a function requirement that any implemented class has to conform to.

you can build an interface with an abstract class


interface blah {
  public function arf( );
}

abstract class blah {
  abstract function arf( );
}

Same end result, ones needs to “implement”, the other “extend”

Interfaces are Java’s alternative to multiple inheritance, even though PHP’s interfaces are not as functional as Java’s.


interface foo{}
interface bar{}
class foobar implements foo, bar{}

There are many discussions about interfaces already. Why not read them instead of making yet another.

If you let me draw an analogy with natural language, classes are nouns and interfaces are adjectives. Nouns can be abstract (“animal”) or concrete (“dog”), but they’re still nouns – they denote Things, while interfaces stand for Properties of Things.

To extend on this for the OP…forgiving the contrived example…lets say you had three classes - BedroomDoor, Gate and GarageDoor. Lets also imagine the BedroomDoor and GarageDoor (and all other Doors) have a range of varying behaviour, but both have exactly the same locking mechanisms. So we have:


class Gate {
   // gate specific behaviour
}

class BedroomDoor {
  // bedroom door specific behaviour

  public function lock($key) {
    $this->lock->insert_key($key);
    $key->turn('clockwise');
  }
}

class GarageDoor {
  // garage door specific behaviour

  public function lock($key) {
    $this->lock->insert_key($key);
    $key->turn('clockwise');
  }
}

Now, as you can see the two lock methods are exactly the same - duplication is evil!

In our imaginary contrived example, all Doors can be locked in the same way (but not Gates, these are bolted shut). We can eliminate this duplication by introducing an abstract class Door which implements this lock method for all of the concrete instances, eliminating the duplication.


abstract class Door {
  public function lock($key) {
    $this->lock->insert_key($key);
    $key->turn('clockwise');
  }
}

class BedroomDoor extends Door {
  // bedroom door specific behaviour
}

class GarageDoor extends Door {
  // garage door specific behaviour
}

Note that we don’t neccesarily have to use an abstract class to eliminate the duplication, we could just inherit from a normal concrete Door class that can be instantiated in its own right, depending on whether it makes sense for a Door to be instantiated on its own.

Now, interfaces - interfaces can be used to specify a specific set of behaviour and that behaviour’s API which classes can implement. As explained above, interfaces are best looked at as adjectives. Both doors and gates can be opened. Thats an interface right there:


interface Openable {
  public function open() { }
}

Both doors (through the abstract Door class) and the gate can be opened, so they can implement the interface.


class Gate implements Openable {
  public function open() {
    if($this->is_locked()) {
      $this->unlock();
    }
    $this->leftSide()->pullOpen();
    $this->rightSide()->pullOpen();
  }
}

abstract class Door implements Openable {
  // our abstract class defines the open function
  // as abstract as we open different types of door
  // differently
  abstract public function open() {}
}

class GarageDoor {
  public function open() { // implement here }
}

class BedroomDoor {
  public function open() { // implement here }
}

By specifying that we will implement the Openable interface, the class is bound by that contract and you will get an error if you forget to implement any of the methods in the interface. Finally, you can take advantage of type hinting in your methods - lets say you need to pass an object into another class to do something - the receiving class doesn’t care what object we pass it as long as it can be opened. We can enforce this using type hinting:


class Foo {
  public function openSomething(Openable $arg) {
    $arg->open();
  }
}

Doing the above ensures that whatever gets passed to the openSomething() method will respond to open() because it implements the Openable interface.

Interfaces/type hinting do not appeal to everybody and some people prefer duck typing which is favored heavily in dynamic languages like Ruby (which doesn’t actually have interfaces or type hinting). The pros and cons of each are best discussed elsewhere though. :wink:

HTH.

This is sorta off topic but. I use an interface for iterators which is obviously a pattern. Should more interfaces be used to describe other patterns other than the iterator?

In my opinion, interfaces are a dumbed down abstract class. I always start with an abstract class, and if I find that I don’t need to implement anything in the class, I change it to an interface.

I do it the other way around. I usually start with interfaces because I don’t want to implement anything yet. And only move to abstract classes when I do.

In my opinion, interfaces are a dumbed down abstract class.

They are dumbed down in what sense?? In PHP the difference between the two is a bit blurred by the fact that under the hood interfaces are just pure abstract classes, but I really don’t see how conceptually interfaces are “dumbed down abstract classes”, they have a totally different function (one that is not so important for dymanically typed languages though).

I did that for a while but got tired of making the change over and over, so now I usually start with an abstract class in the first place.

Conceptually speaking, they aren’t dumbed down abstract classes, practically speaking they are.

This topic has come by here so many times i think if you would search for it it would be of more benefit.

practically speaking they are.

Except the fact that they behave differently (although again in PHP the differences aren’t as profound as other languages).

Pur-lease don’t derail this thread. The last Java vs PHP one was bad enough.

Pur-lease don’t derail this thread. The last Java vs PHP one was bad enough.

Is this a joke or are you just talking to yourself? I never mentioned Java…you on the other hand did twice. If you don’t want a thread to focus on Java then it would be rather foolish to mention it eh?

But as a general rule, I’d say that it’s better to use an interface than a pure abstract class if there is a direct choice. Wouldn’t you agree ?

One could consider an interface as a contract. A class can meet the contract requirements (=implement the interface) by implementing all the methods present in the interface definition.

An abstract class is a class where for one or more methods the signature is defined, but the implementation isn’t available. The objects of a given class can only exist as an instance of the abstract class if the class also implements the abstract methods. One could say that the contract requirements are that a class has to implement all the abstract functions.

As you already might have noticed: each class has an implicit interface, namely the collection of public (abstract or not) methods it exposes… If you look at the contract requirements you could conclude that it’s twice about implementing one or more methods.

On the other hand, when you implement an interface you only sign a contract that ‘can_do’ the methods defined… And when you inherit from an abstract class you not only sign a ‘can_do’ contract but also an ‘is_a’ contract. I would define that as the essential difference.

Actually, implementing an interface is also definition of types, since in OOP type is not only defined by what it knows (attributes), but also what it can do (methods). This means that “is-a” is actually defined by “can do”. E.g. a Bird can be a class, but it is also of the type FlyingObject; not all FlyingObjects are Birds (e.g. Plane), nor all Birds are FlyingObjects (e.g. Chicken); but FlyingObject still is a type, defined by its behavior (e.g. the implementation of the fly() method), not by its data.

In static OOP practice, Bird and Plane would be classes of different hierarchies, while FlyingObject would be an interface (probably called Flyable in Java). In dynamic OOP (Ruby, Python, PHP) practice, there would be no explicit FlyingObject interface; we would use duck typing to determine if an object is a FlyingObject.

I ran a benchmark on abstract classes vs interfaces, and I have some interesting results. Performance wise, you should always use abstract classes.

I created an interface with 1000 methods and an class that implemented it. This took 4.951953 * 10^-4 microseconds to create the class and start 200 instances.

However, when I used an abstract class instead of the interface, it only took 4.053115 * 10^-6 microseconds, again, to create the class and start 200 instances.

This is running off Kubuntu with PHP 5.1.2 on my development machine. 3Ghz with 1GB ram.

So, what are so special about interfaces then if they are 100 times slower?

BTW, the source code is about 3,000 lines, so you can see it here.

So, what are so special about interfaces then if they are 100 times slower

There are a variety of things you can do with interfaces that you cannot do with abstract classes, it doesn’t matter if they are slower. Although at least in my view interfaces are a bit pointless in languages with dynamic typing (they do have documentation value though).