SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 36

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    Jun 2005
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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

  2. #2
    SitePoint Evangelist ClickHeRe's Avatar
    Join Date
    Mar 2005
    Location
    Ottawa, Canada
    Posts
    580
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

    PHP Code:
    interface blah {
      public function 
    arf( );
    }

    abstract class 
    blah 
      abstract function 
    arf( );

    Same end result, ones needs to "implement", the other "extend"
    David

  3. #3
    SitePoint Addict
    Join Date
    Jan 2005
    Location
    United Kingdom
    Posts
    208
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Interfaces are Java's alternative to multiple inheritance, even though PHP's interfaces are not as functional as Java's.
    PHP Code:
    interface foo{}
    interface 
    bar{}
    class 
    foobar implements foobar{} 
    There are many discussions about interfaces already. Why not read them instead of making yet another.

  4. #4
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by iliah
    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) ?
    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.

  5. #5
    SitePoint Guru silver trophy Luke Redpath's Avatar
    Join Date
    Mar 2003
    Location
    London
    Posts
    794
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by stereofrog
    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:

    PHP Code:
    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.

    PHP Code:
    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:

    PHP Code:
    interface Openable {
      public function 
    open() { }

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

    PHP Code:
    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:

    PHP Code:
    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.

    HTH.

  6. #6
    Put your best practices away. The New Guy's Avatar
    Join Date
    Sep 2002
    Location
    Canada
    Posts
    2,087
    Mentioned
    1 Post(s)
    Tagged
    1 Thread(s)
    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?
    "A nerd who gets contacts
    and a trendy hair cut is still a nerd"

    - Stephen Colbert on Apple Users

  7. #7
    SitePoint Zealot Mau's Avatar
    Join Date
    Jan 2006
    Location
    California, USA
    Posts
    134
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  8. #8
    SitePoint Guru dbevfat's Avatar
    Join Date
    Dec 2004
    Location
    ljubljana, slovenia
    Posts
    684
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  9. #9
    SitePoint Guru dagfinn's Avatar
    Join Date
    Jan 2004
    Location
    Oslo, Norway
    Posts
    894
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by dbevfat
    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.
    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.
    Dagfinn Reiersøl
    PHP in Action / Blog / Twitter
    "Making the impossible possible, the possible easy,
    and the easy elegant"
    -- Moshe Feldenkrais

  10. #10
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by dagfinn
    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.
    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 ?

  11. #11
    SitePoint Guru
    Join Date
    Feb 2006
    Location
    Pittsburgh, Los Angeles
    Posts
    706
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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).

  12. #12
    SitePoint Guru dagfinn's Avatar
    Join Date
    Jan 2004
    Location
    Oslo, Norway
    Posts
    894
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Snaily
    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).
    Conceptually speaking, they aren't dumbed down abstract classes, practically speaking they are.

  13. #13
    SitePoint Guru Galo's Avatar
    Join Date
    May 2005
    Location
    Holland!
    Posts
    852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by iliah
    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
    This topic has come by here so many times i think if you would search for it it would be of more benefit.
    Business as usual is off the menu folks, ...

  14. #14
    SitePoint Guru
    Join Date
    Feb 2006
    Location
    Pittsburgh, Los Angeles
    Posts
    706
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    practically speaking they are.
    Except the fact that they behave differently (although again in PHP the differences aren't as profound as other languages).
    Last edited by Snaily; May 5, 2006 at 11:58.

  15. #15
    SitePoint Addict
    Join Date
    Jan 2005
    Location
    United Kingdom
    Posts
    208
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Snaily
    Except the fact that they behave differently (although again in PHP the differences are as profound as other languages).
    Pur-lease don't derail this thread. The last Java vs PHP one was bad enough.

  16. #16
    SitePoint Guru
    Join Date
    Feb 2006
    Location
    Pittsburgh, Los Angeles
    Posts
    706
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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?

  17. #17
    SitePoint Addict timvw's Avatar
    Join Date
    Jan 2005
    Location
    Belgium
    Posts
    354
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  18. #18
    SitePoint Guru BerislavLopac's Avatar
    Join Date
    Sep 2004
    Location
    Zagreb, Croatia
    Posts
    830
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  19. #19
    SitePoint Zealot Mau's Avatar
    Join Date
    Jan 2006
    Location
    California, USA
    Posts
    134
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  20. #20
    SitePoint Guru BerislavLopac's Avatar
    Join Date
    Sep 2004
    Location
    Zagreb, Croatia
    Posts
    830
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Mau
    I ran a benchmark on abstract classes vs interfaces, and I have some interesting results. Performance wise, you should always use abstract classes.
    Sorry, pal, but this is ridiculous.

    This test of yours is going completely against the whole concept of OOP and interfaces.

  21. #21
    SitePoint Evangelist
    Join Date
    Jun 2004
    Location
    California
    Posts
    440
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    BerislavLopac is right if not a bit harsh. Indeed if interfaces are slower than abstract classes that is a bit strange, but interfaces provide better OOP in PHP than do abstract classes. If you really care about time, you should use abstract (according to those results), but if you care about readability and conformity with OOP, use interfaces.
    Happy switcher to OS X running on a MacBook Pro.

    Zend Certified Engineer

  22. #22
    SitePoint Guru
    Join Date
    Feb 2006
    Location
    Pittsburgh, Los Angeles
    Posts
    706
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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).

  23. #23
    SitePoint Guru BerislavLopac's Avatar
    Join Date
    Sep 2004
    Location
    Zagreb, Croatia
    Posts
    830
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I didn't mean that the results are ridiculous, I meant that the idea of testing what he did is ridiculous. It's as if you ride a bus from one point to another while constantly walking inside the bus, and then you compare walking with driving...

  24. #24
    SitePoint Zealot Mau's Avatar
    Join Date
    Jan 2006
    Location
    California, USA
    Posts
    134
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry, I don't understand that analogy. Please enlighten me!

    For the validity of the test, aren't all benchmarks taking it to the extreme? I ran it a few times with just a few methods implemented, and the results were very similar (if different at all).

    True, if you want to conform to the "rules," use interfaces when appropiate. For a slight speed increase, abstract is the way to go. I'm sure there are some major differences between interfaces and abstracts in other languages, but in PHP, interfaces are essentially abstract classes with limited functionality.

    The results are really odd though for PHP. It clearly says that there is some technical difference, but I don't know what. Odd!

  25. #25
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Mau
    For a slight speed increase, abstract is the way to go.
    The old argument of performance rarely make any sense, yet is always brought up. You know that objects are slower to use than strictly procedural code - Would you use that as an argument for not writing OOP code ?

    Quote Originally Posted by Mau
    in PHP, interfaces are essentially abstract classes with limited functionality.
    No. PHP has single inheritance. (and thank GOD for that)


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •