Intermediate
Interfaces
📂 Phase 3: Object-Oriented Programming (Days 11–16) · JavaAn interface is a fully abstract contract — it defines what methods a class must implement, without specifying how. It's how Java achieves complete abstraction and a form of multiple inheritance.
Defining and Implementing an Interface
interface Drawable {
void draw(); // implicitly public and abstract
}
class Circle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
class Square implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a square");
}
}
Why Interfaces Solve the Multiple Inheritance Problem
A class can implement multiple interfaces, unlike extending multiple classes:
interface Drawable {
void draw();
}
interface Resizable {
void resize(double factor);
}
class Shape implements Drawable, Resizable {
public void draw() {
System.out.println("Drawing shape");
}
public void resize(double factor) {
System.out.println("Resizing by " + factor);
}
}
Since interface methods have no body to conflict with, there's no diamond-problem ambiguity even when implementing several interfaces.
Interfaces vs Abstract Classes
| Aspect | Interface | Abstract Class |
|---|---|---|
| Methods | All abstract (default/static methods allowed since Java 8) | Mix of abstract and concrete |
| Fields | Only public static final (constants) | Any type of field |
| Multiple inheritance | A class can implement many | A class can extend only one |
| Constructors | Not allowed | Allowed |
Default Methods (Java 8+)
Interfaces can now provide a default implementation, which implementing classes may override if needed:
interface Greetable {
default void greet() {
System.out.println("Hello!");
}
}
class Person implements Greetable {
// can use the default greet(), or override it
}
new Person().greet(); // Hello!
Polymorphism Through Interfaces
Drawable[] shapes = { new Circle(), new Square() };
for (Drawable d : shapes) {
d.draw(); // calls the correct implementation for each object
}
Interview tip: "Can an interface extend another interface?" — Yes, using extends, and an interface can extend multiple interfaces at once (unlike classes, which can only extend one class).