3

How would you - as an experienced OOP developer - describe the difference between an abstract class & an interface to a beginner, learning the concepts?

Comments
  • 1
    My understanding of this is, that interfaces define only whivh methods must the class have and abstract classes define the most methods and the developer must define some.
  • 3
    A example: human is a abstract class implemented by male and female classes. A interface are more like a behaviour. In the human case perhaps feelings or some ability like angry, happy, sortable, fuckable.

    I abstract class can contain logic a interface dont.

    Some languges allow only one class inheritance (java) but allows several interfaces for one class.

    Does that give you a better understanding?
  • 2
    @devlajf I like the point you raise for an abstract class containing logic. (BTW I understand the concepts myself, I was curious to see the analogies & metaphors others could come up with :) )

    Another good definition I found was on StackOverflow:
    An interface is like a contract - defining precisely what something looks like or seems.
    An abstract class can so the same, but flesh out certain bits where every implementation of said abstract class should have a specific method in common.
  • 0
    As mentioned above, a interface can be explained as a contract, containing the method names (not the implementation, just the name) of methods a class implementing it MUST have to be able to run/compile. An abstract class can be thought of as how a human implements animal. You can't initialize animal, but all animals have a already implemented .sleep() function which can be derived from the animal abstract class instead of defining it in itself. That's pretty much how I got it.
  • 0
    Interface defines the contract of what an object that implements the interface can do. It will keep things loosely coupled because you program to the interface and not an implementation.

    Abstract class however can also provide and interface in terms of what an object can or must do, but couples you to the implementation. You can however implement an interface using an abstract class that provides a base implementation for an interface, and let the abstract class define the things that the developer MUST implement.
  • 0
    In addition; think of a car having an IEngine interface which defines what the engine can do, how its connected etc. Any manufacturer conforming to that interface can then create an engine that fits in the car. Because of this, engines can be exchanged. Same goes for USB connectors which in fact are (hardware) interfaces. For any device you make; as long as it has USB connector it will work with USB.

    Abstract class on the other hand will just be the basic frame for engines of a specific manufacturer. The frame, connectors and some other basic stuff may be the same but the actual implementation will be different for each engine.
Add Comment