CodeBlanks Logo Icon CodeBlanks

interface vs abstract

PHP course · Intermediate · Lesson 51/115

Learn the difference between interface and abstract class and when to use each.

interface vs abstract class

An abstract class cannot be instantiated directly with new and may contain abstract methods (bodyless) that subclasses implement. For now, that's all we need for the comparison.

The key difference: a class can extends only one abstract class (single inheritance), but can implements multiple interfaces.

Also, an interface holds no properties; only method signatures and constants. An abstract class can hold properties, a constructor and concrete methods. An interface is a pure contract; an abstract class shares partial implementation.

When interface, when abstract?

An interface is a pure contract; it shares no common code among implementing classes. It is ideal for adding the same capability (role) to unrelated classes: Loggable, Serializable, Cacheable.

An abstract class provides a common base and partial implementation. When building a hierarchy like Dog, Cat under Animal, you collect shared properties and methods in the abstract class.

In short: interface for capability, abstract class for a common base. They can be combined: class Dog extends Animal implements Loggable.

Test yourself

  1. How many interfaces can a class implement?

    • Unlimited
    • Only one
    • At most two
    • None
    Show answer

    Unlimited — Correct. A class can implement unlimited interfaces separated by commas: implements A, B, C.

  2. abstract class and interface together

    class Dog extends Animal ____ Loggable, Cacheable {
        // ...
    }
    Show answer
    class Dog extends Animal implements Loggable, Cacheable {
        // ...
    }
  3. Match the interface vs abstract differences

    interface
    Unlimited implementation
    abstract class
    Single inheritance
    property
    in abstract class
    pure contract
    in interface
  4. When should an interface be preferred?

    • When common code will be shared
    • When shared properties are needed
    • When a single base class hierarchy is built
    • When the same capability is added to unrelated classes
    Show answer

    When the same capability is added to unrelated classes — Correct. An interface is ideal for adding the same capability (role) to unrelated classes.

All lessons in Intermediate