Interface in Java
Problem
An interface declares a set of method signatures with no bodies, and any class that implements it must supply real code for every one of them.
Define a Notification interface with a send method, and implement it in a single class.
Java Program
interface Notification {
void send(String message);
}
class EmailNotification implements Notification {
public void send(String message) {
System.out.println("Sending notification: " + message);
}
}
public class InterfaceDemo {
public static void main(String[] args) {
Notification n = new EmailNotification();
n.send("Order shipped");
}
}Output
Core Logic
Declaring a method with no body in an interface, then supplying that body in exactly one implementing class, is the simplest form the interface contract can take.
- 1
interface Notificationdeclaresvoid send(String message);with no implementation. - 2
class EmailNotification implements Notificationcommits to supplying that method. - 3Its
send(String message)method provides the actual behavior — printing the message here. - 4
Notification n = new EmailNotification();lets the object be referred to by the interface type, even though only one class implements it.
n.send("Order shipped") runs EmailNotification's implementation, printing "Sending notification: Order shipped".Key Point: An interface by itself can never be instantiated — new Notification() wouldn't compile — only a class that implements it, and supplies every method, can be constructed.
Key Concepts
Approach 2: Java 8
interface Notification {
void send(String message);
}
public class InterfaceDemoLambda {
public static void main(String[] args) {
// The lambda's body implements send() directly — no class needed
Notification n = message -> System.out.println("Sending notification: " + message);
n.send("Order shipped");
}
}
Output
Core Logic
Because Notification has exactly one abstract method, a lambda can supply its body directly, standing in for an entire implementing class.
- 1
Notificationis left completely unchanged — it still just declaresvoid send(String message);. - 2
Notification n = message -> System.out.println("Sending notification: " + message);assigns a lambda straight to aNotificationreference. - 3The lambda's single parameter,
message, and its body implementsend— inferred entirely from the interface's one method signature. - 4No
EmailNotificationclass is declared at all — the lambda itself is the implementation.
n.send("Order shipped") runs the lambda's body directly, printing the same "Sending notification: Order shipped" the class-based version produced.Key Point: A lambda can only replace a named class this way because Notification has a single abstract method — this exact substitution wouldn't compile for an interface with two or more methods to implement.