Search code examples
phpinterfaceabstract-classconceptual

Abstract Class vs. Interface


I have searched around SO as well as the rest of the web for a good answer but I have't found one that I really understand. I am going to present this in a different way and hopefully the answers will help others as well.

As far as I understand, the two concepts have the same rules except an abstract class is more flexible due to the method implementation ability. Also, I am aware you can implement multiple interfaces and only extend a single class but I'm sure there are more differences than the two I mentioned.

Please look at the two snippets of code and give me an example what I can do with each of my examples that would make me want or not want to use the other.

Abstract Class

abstract class Foo {
    abstract public function getValue();
    abstract public function setValue($value); 
}


class myObj extends Foo {
    function getValue() {

    }
    function setValue($value) {

    }
}

Interface

interface Foo {
    public function getValue();
    public function setValue($value);
}

class myObj implements Foo {
    function getValue() {

    }
    function setValue($value) {

    }
}

Solution

  • To resume the idea (globally, not in detail):

    inheritance
    

    is the notion to extend from something, and optionally add some new feature or override some existing feature (to do differently). But using inheritance, you share a big part of code with the parent. You are a parent + some other things.

    interface
    

    is representing some abilities (we says a class is implementing an interface to says that it has these abilities). An interface can be implemented by 2 classes which are completely different and do not share their code (except for methods they implements). When A and B are implementing interface C, A is not a B and B is not a A.

    And one of the reason for interface is indeed to allow programmer to do the same as they could do with multi-inheritance, but without multi-inheritance problems.

    This notion is used in some programming languages like JAVA, PHP...