Defining & Implementing
Interfaces
Learn how Java interfaces create contracts that classes must follow: defining abstract behaviors and building flexible, reusable code architectures.
What Is an Interface?
An interface in Java is a reference type that defines a contract: a set of method signatures that any implementing class must provide. Think of it as a blueprint that says what a class can do, without saying how it does it.
Why Use Interfaces?
Anatomy of an Interface
The Syntax Rule
What Can an Interface Contain?
Interface vs Abstract Class
| Interface | Abstract Class | |
|---|---|---|
| Methods | Abstract + default | Abstract + concrete |
| Fields | Constants only | Any fields |
| Constructors | ✕ No | ✓ Yes |
| Multiple | ✓ Many interfaces | ✕ One class only |
| Keyword | implements | extends |
How It Fits Together
How to Apply It
public interface Name and list abstract method signatures.implements Name to the class header.Drawable d = new Circle();Example 1: Simple Interface
Example 2: Multiple Interfaces
Example 3: Polymorphism in Action
Default Methods in Interfaces
A default method has a body inside the interface itself. Implementing classes inherit this method automatically but can override it if needed.
Interface Inheritance
Interfaces can extend other interfaces using the extends keyword. A class implementing Turbo must provide bodies for both move() and boost().
Common Mistakes
new Drawable(). Interfaces have no constructor: use a class that implements it.Summary Table
| Concept | Details |
|---|---|
| Keyword | interface to define, implements to use |
| Methods | Abstract (no body) + default (with body) |
| Fields | public static final constants only |
| Multiple | A class can implement many interfaces |
| Inheritance | Interfaces extend other interfaces |
| Instantiation | Cannot create an interface object directly |
| Use case | Shared behavior across unrelated classes |
Question 1 of 5
Which keyword does a class use to adopt an interface in Java?
Question 2 of 5
What happens if a class implements an interface but does not provide a body for one of its abstract methods?
Question 3 of 5
Consider the following code:
public interface Printable {
void print();
}
public class Report implements Printable {
void print() {
System.out.println("Report");
}
}
What is wrong with the Report class?
Question 4 of 5
How many interfaces can a single Java class implement?
class X implements A, B, C { ... }. This is one of the key advantages of interfaces over class inheritance.Question 5 of 5
Consider the following interfaces and class:
public interface Drivable {
void accelerate();
default void honk() {
System.out.println("Beep!");
}
}
public class Truck implements Drivable {
public void accelerate() {
System.out.println("Truck speeds up");
}
}
Which statement about the Truck class is correct?