Search code examples
oopinterfaceabstract-classooad

Is there a benefit to having both an abstract class and an interface?


I started out with a generic interface called ILogin. The interfaces requires that you implement two properties: UserID and Password. I have many login-type classes that implement this interface. As my project grew and grew, I found that many classes repeated the UserID and Password code. Now I decide that I need a base Login class.

Is it proper to create an abstract base Login class that implements the ILogin interface and have all of my concrete classes just inherit from the abstract class and override when necessary? Originally I was thinking there would be no problem with this. Then I started think that ILogin was probably unneeded because it'll likely only ever be implemented by my abstract class.

Is there a benefit to keeping both the abstract class and the interface around?

Thanks!


Solution

  • Definitely. Let's think of a concrete example.

    Say we have an abstract class Animal. Say, we make some subclasses Cat, Dog, Mosquito, and Eagle. We can implement its Eat(), Breathe(), Sleep() methods of the abstract class Animal.

    So far, so good. Now, let's say we want to have the Fly() method for the Mosquito and Eagle classes. Since these two organisms aren't really well-related (one is a bird, another is an insect) it wouldn't be easy to come up with a common ancestor for the two that we can have as an abstract class. This would best be implemented by an interface IFly.

    The IFly interface can have a Fly() method to be implemented. Both Mosquito and Eagle classes can both be subclasses of the abstract class Animal and implement the interface IFly and be able to Eat(), Breathe(), Sleep() and Fly() without having some type of odd ancenstral relationship between the two classes.