UML Class Diagram – Choosing Between Abstract Class and Interface

abstract classclass-diagraminterfacesuml

I am modeling a class diagram and have spotted an opportunity to simplify it slightly. What I want to know is, would this it be better to implement an abstract class or an interface?

The scenario is this, I have the classes:

  • Artist
  • Genre
  • Album
  • Song

All of which share the methods getName, setName, and getCount (playcount that is). Would it be best to create an abstract 'Music' class with the aforementioned abstract methods, or should I create an interface, since the classes that implement the interface have to include all of the interface's methods (I think, correct me if I'm wrong).

I hope I've given enough detail, please ask questions if I haven't.

Thanks!

Best Answer

You should create an abstract class.

Generally speaking, a song can consist of a Title / Artist / Album / Genre. All of those are just a string of data which can be handled the same way. By using an abstract class you don't have to write mentioned "getName", "setName" and "getCount" more than once, which sounds pretty neat.

Using an interface would just tell you that the functions should exist in each class, but you'd still have to write them separately. However, if you come up with methods they all have in common, but which work differently for each class, I suppose an interface would make more sense.

What bugs me though is that you want them to be classes. For example, since you would want an album to have it's own "Times played", you'd have to make sure that there's only one instance of that specific album. Each time a new song is added, you'd either have to search through all existing classes with that name and set a pointer or something similar to the already existing one.

Then again, the good part about using an album as an instance of a class, is that it's possible to have several albums with the same "name" without counting them as the same album. Err.. anyways, my mind has drifted away and this is not really related to the question.