I'm refactoring my code, so I need make decision about interface or abstract class.
I have base class Player and classes that inherit base class which are called VideoPlayer, MusicPlayer and so on. Base class have abstract method with no implementation (Play).
So, What is preferable way? Put Play in interface or leave it in abstract class. Play in MusicPlayer is not same like Player in VideoPlayer. I do that in C#.
class Player
{
abstract void Play();
}
class VideoPlayer : Player
{
void Play()
{
//Some code.
}
}
class MusicPlayer : Player
{
void Play()
{
//Some code.
}
}
One common thing is to do both
a) provide the interface. And use the interface when you consume the object (ie invoke the play method).
b) provide a base class that implements the interface for the case where there is common plumbing; common methods etc. This is a helper for implementers to optionally use
IN this way an implementer of IAmAPlayer can simply implement that interface or if their use case matches your base class they can use that.
If you don't have any base functionality you want to inherit, use an interface. Abstract classes are used when you have a partial implementation you want to be inherited.
Generally if it's just to signify that a method can be called you'd use an interface. The interface is partially designed to solve the single inheritance problem. If you're not implementing common methods in the parent, use an interface.
Keep it simple. If you can use an interface do that. If you can't use an interface use an abstract class.
One thing to consider, interfaces require all its properties and methods to be implemented where abstract classes do not. Minor point but sometimes you need to support multiple versions of an assembly.
You need to understand the difference between Interface Inheritance and Class inheritance.
Abstract classes are used for Modelling a class hierarchy of similar looking classes (For example Animal can be abstract class and Human , Lion, Tiger can be concrete derived classes)
Interface is used for Communication between 2 similar / non similar classes which does not care about type of the class implementing Interface(e.g. Height can be interface property and it can be implemented by Human , Building , Tree. It does not matter if you can eat , you can swim you can die or anything.. it matters only a thing that you need to have Height (implementation in you class) )
Now you will understand here that for your example you may need to have both. If you are sure of the possibility of consumption of Play method amongst many other classes its very good to have interface implementation so that others will use method via Interface.