Method overriding
A parent type may say “every payment method can pay,” but each child pays its own way. Method overriding is when a child class (or a class that implements an interface) writes its own version of a method it inherited. When the program runs, the child’s version is the one that is used.
The parent names the operation. Each child answers “here is how I do it,” with the same name and parameter types.
Put @Override above the method. The compiler then checks that the parent really has this method. If you misspell the name, you get an error. Without it, Java adds a new method.
Polymorphism
Polymorphism means “one type, many forms.” You write code for one type, usually an interface or a parent class. At runtime (while the program runs), the real object can be any class that fits it. Java calls that object’s overridden method.
For example, the variable type is PaymentMethod, but the object might be a CreditCard or a UPI. When you call paymentMethod.pay(100), Java runs the actual object’s version: CreditCard.pay or UPI.pay.
Example
// Type is the interface
PaymentMethod pm1 = new CreditCard("4111");
PaymentMethod pm2 = new UPI("user@bank");
// Same call, different behavior: that's polymorphism
pm1.pay(100); // CreditCard's pay() runs
pm2.pay(100); // UPI's pay() runs
// Processor doesn't care which implementation it gets
public void processPayment(PaymentMethod method, double amount) {
method.pay(amount); // Works for CreditCard, UPI, Paypal, etc.
}Overriding is the writing part: each class has its own pay(double). Polymorphism is the using part: processPayment only needs “something that can pay.”
Where you see it in this repo
- OCP (add types without editing old code):
PaymentProcessor.processPayment(PaymentMethod, double)is polymorphic overPaymentMethod. Each payment type overridespay(). (The repo classes take no constructor arguments, unlike the simplified example.) - DIP (depend on the interface):
NotificationServiceholds aNotificationChanneland callssend(). It works with Email or SMS. - Factory:
Logistics logistics = LogisticsFactory.getLogistics(mode); logistics.send();works the same for Road or Air. - LSP (a child can replace its parent):
readAnyFile(ReadableFile file)callsfile.read(). It works forReadOnlyFileandWritableFile, since both are aReadableFile. - @Override is used on most interface implementations (for example
Paypal,Wallet) and onclone()in the Prototype pattern.UpiinBasics/OOP/exampleleaves it out.