Nested Interface in Java
An interface can be declared inside a class or another interface, just like a nested class. A nested interface belongs to its outer type by name, such as Bank.Listener or Map.Entry, which tells readers exactly what it's for. Nested interfaces are always implicitly static: an interface has no instance state, so it never needs an outer object.
A Bank with a Listener
Alerts.java▶ Try it
import java.util.Map;
import java.util.TreeMap;
public class Alerts {
static class Bank {
interface Listener {
void onDeposit(String holder, long amount);
}
private Listener listener;
void setListener(Listener listener) { this.listener = listener; }
void deposit(String holder, long amount) {
// ... update the balance ...
if (listener != null) {
listener.onDeposit(holder, amount);
}
}
}
static class SmsAlert implements Bank.Listener {
public void onDeposit(String holder, long amount) {
System.out.println("SMS: Rs. " + amount + " credited to " + holder);
}
}
public static void main(String[] args) {
Bank bank = new Bank();
bank.setListener(new SmsAlert());
bank.deposit("Navika", 2500);
Map<String, Integer> marks = new TreeMap<>(
Map.of("Srihitha", 88, "Advitha", 93));
for (Map.Entry<String, Integer> e : marks.entrySet()) {
System.out.println(e.getKey() + " -> " + e.getValue());
}
}
}Output
SMS: Rs. 2500 credited to Navika
Advitha -> 93
Srihitha -> 88How it works
Bank.Listeneris declared insideBank. Its full name says it's a listener for bank events.SmsAlert implements Bank.Listener: outsideBank, the interface is referred to by its qualified name.Bankcalls the listener whenever money arrives, without knowing whether it sends an SMS, an email or a push notification. This listener (or callback) pattern is everywhere in event-driven code.Map.Entryis the JDK's best-known nested interface: one key-value pair of a map.entrySet()returns all of them.
The Rules
| Where it's declared | Implicit modifiers | Can be private? |
|---|---|---|
| Inside a class | static | Yes, any access level |
| Inside an interface | public static | No, always public |
Nested enums and records are implicitly static too, for the same reason: they never need an outer object.
Common Mistakes
Writing static on a nested interface. It's allowed but redundant.
Implementing Listener without the outer name from another file. Use Bank.Listener, or import it.
Nesting general-purpose interfaces. A widely used interface belongs at the top level.
Practice
- Easy: Add an
EmailAlertclass that implementsBank.Listener, and switch the bank to it. - Harder: Change
Bankto hold aList<Bank.Listener>so several listeners are notified on every deposit, and register bothSmsAlertand an anonymous listener.
Key Takeaways
Was this tutorial helpful?
Lesson 173 of 482