Method Overriding
Method Overriding is a process in Java where a subclass provides a specific implementation for a method that is already defined in its superclass.
Key Points
1. Method Overriding requires inheritance.
2. To override a method, the subclass method must have the same name, return type, and parameter list as the superclass method.
3. During method overriding:
- The subclass method definition is used (exposed).
- The superclass method definition is hidden.
- This concept is sometimes referred to as method hiding (though strictly speaking, method hiding is for static methods).
4. Only instance methods (non-static methods) can be overridden.
5. Method overriding cannot be achieved within the same class; it only works between subclass and superclass.
Example
System.out.println("Animal makes a sound");
class Dog extends Animal {
System.out.println("Dog barks");
public static void main(String[] args) {
a.sound(); // Output: Dog barks
Important Notes
- Static methods cannot be overridden (they are hidden instead).
- Method overriding is a runtime polymorphism (dynamic binding) feature in Java.
- The @Override annotation is optional but recommended; it helps the compiler catch mistakes.
Comments
Post a Comment