Interfaces Versus Abstract Classes

Posted by

While you use an interface to specify the form that something must have, it
does not actually provide the implementation for it. In this sense, an interface
is a like an abstract class. The abstract class must be extended in exactly the
manner that its abstract methods specify.
An interface differs from an abstract class in the following ways:

  • An abstract class is an incomplete class that requires further specialization
    in child classes. The subclasses are closely related to the parent. An
    interface doesn’t have any overtones of specialization that are present
    with inheritance. It merely says, “We need something that does ‘foo’ and
    here are the ways that users should be able to call it.”
  • A class can implement several interfaces at once, whereas a class can
    extend only one parent class.
  • Interfaces can be used to support callbacks (inheritance doesn’t help with
    this). This is a significant coding idiom. It essentially provides a pointer to
    a function, but in a type-safe way

Here’s the bottom line: You’ll probably use interfaces more often than abstract
classes. Use an abstract class when you want to initiate a hierarchy of more
specialized classes and provide a partial implementation with fine control over
what is private, public, protected, etc. Use an interface when you need
multiple inheritance of design to say, “This class has behavior (methods) A, B,
and C.”
An interface can be extended, but only by another interface. It is legal for a
class to implement an interface but only have some of the methods promised
in the interface. You must then make it an abstract class that must be further
extended (inherited) before it can be instantiated.

Leave a Reply

Your email address will not be published. Required fields are marked *