Method Overriding & @Override Annotation Rules
1Concept
Method Overriding allows a subclass to provide a specific implementation of a method defined in its superclass. Rules: 1. Exact same method name and parameter types; 2. Return type must be identical or a subtype (Covariant Return Type); 3. Access level cannot be more restrictive; 4. Cannot throw broader checked exceptions.
2Architecture Diagram
Superclass: public Number calculate() (Broader return type) Subclass: public Integer calculate() (Covariant subtype return: VALID!)
3Code Example
Core Java
public class MethodOverridingDemo {
static class PaymentService {
public String processPayment(double amount) {
return "Standard payment processed: $" + amount;
}
}
static class CryptoPaymentService extends PaymentService {
@Override
public String processPayment(double amount) {
return "Crypto payment processed via Blockchain: $" + amount;
}
}
public static void main(String[] args) {
PaymentService service = new CryptoPaymentService(); // Upcasting
System.out.println(service.processPayment(250.0)); // Polymorphic dispatch
}
}4Expected Output
CryptoPaymentService: Crypto payment processed via Blockchain: $250.0
5Key Takeaways
- ✓Always apply `@Override` annotation; it instructs the compiler to verify matching method signatures.
- ✓Private, static, and final methods CANNOT be overridden.
- ✓Subclasses can broaden access (e.g. protected -> public), but never restrict it (e.g. public -> private).