Interfaces
An interface is a contract: a list of methods a class promises to provide.
What you will learn
- Define an interface
- Implement it in a class
- See why interfaces give flexibility
A contract of abilities
An interface lists method names with no code inside — just a promise. Any class that implements the interface must provide the actual code for those methods. Think of it as a contract: sign it, and you agree to deliver these abilities.
public interface Playable {
void play(); // no body — just the promise
void stop();
}Note: Output: (No output — an interface has no code to run. It only states which methods an implementing class must provide.)
A class fulfils the contract
public class MusicPlayer implements Playable {
@Override
public void play() {
System.out.println("Playing music...");
}
@Override
public void stop() {
System.out.println("Music stopped.");
}
}Note: Output: (No output yet — the class now fulfils the contract by writing real code for play() and stop(). If it left one out, Java would refuse to compile.)
Using it
public class Main {
public static void main(String[] args) {
Playable device = new MusicPlayer();
device.play();
device.stop();
}
}Note: Output:
Playing music...
Music stopped.
Notice the variable type is Playable (the interface), but the real object is a MusicPlayer. Any class that implements Playable would work here — that is the flexibility interfaces give.
Interface vs inheritance
| Inheritance (extends) | Interface (implements) |
|---|---|
| Says: a Dog IS AN Animal | Says: a class CAN DO these things |
| Shares actual code | Shares only a promise (the method list) |
| One parent only | A class can implement MANY interfaces |
Tip: A class can implement several interfaces at once: class Phone implements Playable, Recordable. This is how Java lets one class take on many roles without the limits of single inheritance.
Q. What must a class do when it implements an interface?
✍️ Practice
- Define an interface
Shapewith a methodarea()and implement it in aCircleclass. - Create a Circle through a
Shapevariable and callarea().
🏠 Homework
- Create a
Drawableinterface with adraw()method and have two different classes implement it. Call draw() on each.