What are interfaces?
An interface is a contract or blueprint for a class.
Interfaces define what a class does, but not how it does it.
public interface Playable {
void play();
}Why are interfaces useful?
how to use interfaces in your code
public class Video implements Playable {
@Override
public void play() {
//play the video
}
}
public class Audio implements Playable {
@Override
public void play() {
// play the audio
}
}Classes implement interfaces to provide the how
What’s the point of interfaces?
Interfaces allow us to write code that is agnostic to the implementation
public class Player{
public void play(Playable playable) {
playable.play();
}
}
public class Main {
public static void main(String[] args) {
Player player = new Player();
player.play(new Video());
player.play(new Audio());
}
}