Interfaces
Interfaces
An interface defines a contract: a set of method signatures (and optionally constants) that a class must implement. Unlike a class, a class can implement multiple interfaces. Interfaces are used for abstraction and for dependency injection in interviews and real code.
Defining an interface
Methods in an interface are abstract by default (no body). From Java 8 onward you can also have default and static methods with a body.
javapublic interface Drawable { void draw(); // no body, must be implemented default void describe() { System.out.println(\"A drawable shape\"); } }
Implementing classes must provide draw(); they can use or override describe().
Implementing an interface
A class implements an interface and must provide implementations for all abstract methods:
javapublic class Circle implements Drawable { private double radius; public Circle(double radius) { this.radius = radius; } @Override public void draw() { System.out.println(\"Drawing a circle of radius \" + radius); } }
A class can implement several interfaces:
code
public class X implements A, B, C { ... }Why interfaces matter
- Abstraction: Callers depend on the interface, not a concrete class. You can swap implementations (e.g. real service vs mock in tests).
- Multiple behavior: A class can implement many interfaces (e.g.
ComparableandSerializable). - APIs and design: Libraries expose interfaces (e.g.
List) so you code against the contract. Very common in interview discussions about design.