What does implements mean?
An interface lists methods without code. When a class implements it, the class promises to write the code for every one of those methods. The compiler checks the promise: leave a method out, and the class does not compile. After that, the class can be used anywhere the interface is expected.
Simple terms
- Interface = a named contract, such as “can take a payment.”
implements= “this class keeps that contract, so you can use it wherever the contract is asked for.”
Pause and predict: if CreditCard forgets pay(double amount), will the error appear when a customer pays, or while the code compiles? It appears at compile time.
A class can implement many interfaces at once, for example class MultiMachine implements Printer, Scanner, Copier. Separate the names with commas.
Example
public interface PaymentMethod {
void pay(double amount);
}
// This class MUST have a method: void pay(double amount)
public class CreditCard implements PaymentMethod {
private String cardNumber;
public CreditCard(String cardNumber) {
this.cardNumber = cardNumber;
}
@Override
public void pay(double amount) {
System.out.println("Paying " + amount + " using card " + cardNumber);
}
}PaymentMethodsays: “You must havepay(double amount).”CreditCardimplementsPaymentMethod, so it must writepay(double amount). Here it prints the amount and the card number.@Overridemarks the method as the one that fills the contract. If the name or parameters do not match, the compiler reports an error.- The constructor and the
cardNumberfield are normal class code. They are not part of the contract.
Where you see it in this repo
- OCP:
CreditCard,DebitCard,UPI,Paypalall implementPaymentMethod. - DIP:
EmailService,SMSServiceimplementNotificationChannel. - ISP:
SimplerPrinterimplementsPrinter;MultiPurposeMachineimplementsPrinter,Scanner, andCopier. - Factory:
Road,AirimplementLogistics. - Prototype:
WelcomeEmailimplementsEmailTemplate.