Search code examples
inheritanceinterfaceabstract-classmultiple-inheritanceextends

Interface vs Abstract and Inheritance


I have already looked upon the the usage of interface, abstract classes and inheritance. I see that each have their uses but, I am still kind of confused.

I know that generally a class can extend only another class, although some may support multiple inheritance, but it can implement more than one interface (which is probably the main reason for using an interface). However this class can also be extended by another class If I am correct. I have also seen that abstract classes may be faster than interfaces and can have non-static final variables.

So, I am still not sure about when is it better to use which. Maybe by giving some examples this can be better understood. I am not against using any but I think there is something that I do not see. Further explanations might help as well. Thanks in advance.


Solution

  • Inheriting from a base class is useful if you want to use the same code as the base class and extend it with extra functionality.

    Vitual and abstract are related to this. You can make a virtual method with a base implementation. A descendant class can (optionally) change or add to this implementation. An abstract class is a base class that is incomplete in itself. An abstract method is declared, but has no implementation yet. A descendant class must provide an implementation. This is useful if the base class implements a flow, but a part of that flow needs to be implemented by another class. The base class needs to be able to call that part, which is where declaring an abstract method comes in sight.

    Interfaces are a different story. An interface is a contract about which methods exist in a class, but they can be implemented by two completely unrelated classes. This is convenient, because you can make small interfaces for small pieces of functionality. For example, something that can be saved can implement ISavable, which just enforces the existence of the method 'Save'. Two completely different classes can implement this, allowing for instance a Save All functionality to just save everything that can be saved.

    Multiple inheritance is a specific language feature, that is not available in many languages, although in many languages you can have a similar effect by using interfaces and the delegate design pattern.