Method overriding in Java
✅ What is Method Overriding in Java?
Method overriding in Java occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.
The overridden method in the subclass should have:
-
Same method name
-
Same return type (or subtype - called covariant return type)
-
Same parameter list
๐ง Purpose of Overriding
To implement runtime polymorphism, where the method that gets called depends on the object's runtime type, not the reference type.
๐ Example of Method Overriding
๐งพ Output:
๐ Key Points about Method Overriding
| Rule / Feature | Description |
|---|---|
| Same Signature | Name and parameters must be identical |
| Access Modifier | Can’t be more restrictive than the superclass method |
| Return Type | Must be the same or a subtype (covariant) |
| @Override Annotation | Optional but recommended – helps catch errors |
| Static/Private/Final Methods | Cannot be overridden |
| Constructors | Cannot be overridden |
๐ Access Modifier Example
❌ Invalid Overriding Example (Compile-time Error)
Explanation: show() in Parent is private – not visible to Child.
๐ Method Overloading vs Method Overriding
| Feature | Method Overloading | Method Overriding |
|---|---|---|
| Occurs in | Same class | Between superclass and subclass |
| Parameters | Must differ | Must be the same |
| Return Type | Can differ | Must be same or subtype |
| Access Modifier | Any | Cannot be more restrictive |
| Polymorphism Type | Compile-time | Runtime |
๐งช Real-world Analogy
Think of a base class Printer that prints documents. A ColorPrinter (subclass) can override the method to print in color, while BlackAndWhitePrinter prints in black-and-white – same method, different behavior.
Comments
Post a Comment