Explaning with your own scenario:
Interface
interface Player{
public void play();
public void pause();
public void stop();
}
Classes which are implementing Player
Intreface;
class AudioPlayer implements Player{...}
class VideoPlayer implements Player{...}
Some extra class. Meaningless but seems relevant
Class PlayList{}
An enum who plays important role;
enum MEDIAPLAYER {
AUDIO,VIDEO;
public Player getPlayer() {
switch (this) {
case AUDIO:
return new AudioPlayer();
case VIDEO:
return new VideoPlayer();
default:
return new AudioPlayer();
}
}
}
Using your code
Player testPlayer = MEDIAPLAYER.getPlayer();
:
testPlayer.play();
Now if any new player is added, its entry will go to MEDIAPLAYER
which is returning Player
type object. So everyone would have to implement Player
Another approach:
You can create an abstract class, say MasterPlayer
, who is having all the abstract methods Player
interface has. In addition, MasterPlayer
will have some additional methods like managing PlayList