Unit 4 · The Four Pillars in Depth · 9 min
Interfaces
An interface defines a contract a class promises to follow. It can declare abstract methods and may also provide default or static methods. A class can implement many interfaces.
Why this matters
Java does not allow a class to extend two classes, but a class can implement many interfaces — that is how Java achieves multiple inheritance of type.
Real-life analogy
A driving licence is a contract: it says you can drive. It does not say how you learned. Anyone holding it can be handed a car.
Syntax
Syntax
interface Name {
void doSomething(); // public abstract by default
}
class X implements Name { public void doSomething() { } }Example
Java
interface Printable {
void print();
}
interface Showable {
void show();
}
class Report implements Printable, Showable {
String title = "Semester Report";
@Override
public void print() {
System.out.println("Printing: " + title);
}
@Override
public void show() {
System.out.println("Showing: " + title);
}
}
public class Main {
public static void main(String[] args) {
Report r = new Report();
r.print();
r.show();
Printable p = r; // interface reference
p.print();
}
}Output
Printing: Semester Report Showing: Semester Report Printing: Semester Report
Step by step
- 1A method declared without a body in an interface is public and abstract by default.
- 2`implements Printable, Showable` promises to define both methods.
- 3Overriding methods must be declared public, because interface methods are public.
- 4`Printable p = r;` works because Report IS-A Printable. This enables loose coupling.
Key points
- Use implements for interfaces, extends for classes
- A class can implement many interfaces
- Interface fields are public static final by default
- Since Java 8 interfaces may also have default and static methods
Common mistakes
- Forgetting the `public` modifier on the implementing method
- Trying `new Printable()` — interfaces cannot be instantiated
- Using extends when you meant implements
Try it yourself
- Write a Drawable interface and implement it in Circle and Square.
- Make a class implement two interfaces and call both methods.