What is an interface?
Sometimes your code needs “something that can send a message,” whether email or SMS. An interface lets you say that.
An interface is a contract. It lists what a class must be able to do, such as send(String message). It does not say how. Classes that implement (agree to follow) it write the code.
It is like a job description: “Anyone hired for this role must be able to do X and Y.” The interface says what callers may ask for. Each class decides how.
Newer Java also allows default, static and private methods with a body, but the main job is still to list what.
Why use it?
- So you can program to the contract, not to one class. Your code asks for “something that can send,” not for
EmailService. - So you can swap implementations without changing other code, for example email to SMS.
Simple example
// Contract: "Anyone who implements this must have a send method."
public interface NotificationChannel {
void send(String message);
}
// One implementation
public class EmailService implements NotificationChannel {
@Override
public void send(String message) {
System.out.println("Email: " + message);
}
}
// Another implementation
public class SMSService implements NotificationChannel {
@Override
public void send(String message) {
System.out.println("SMS: " + message);
}
}sendinNotificationChannelends with;and has no{ ... }body. That is the contract.EmailServiceandSMSServiceboth “sign” it withimplements NotificationChanneland write their ownsendbody.@Overridetells the compiler: “this fulfils a method from the contract.” If it does not match, the code will not compile.- A caller can hold either object as a
NotificationChanneland callsend("Hi"). It printsEmail: HiorSMS: Hi.
Where you see it in this repo
- SOLID DIP (depend on the contract):
NotificationChannelinPrinciples/SOLID/DIP/GoodCode. (ConceptsDemo.javacalls itNotifier.)NotificationServiceuses the interface, not Email or SMS. - SOLID OCP (add types without editing old code):
PaymentMethod. Many payment types implementpay(amount). - Factory pattern:
Logistics. Road and Air implement it. - Prototype:
EmailTemplateis the contract forclone,setContentandsend.