Overriding Methods
Overriding Methods
Understanding Method Overriding
- Method overriding is a key feature of inheritance in Java programming, where a subclass provides a specific implementation of a method that is already provided by its superclass.
- It is used for runtime polymorphism, and code readability is improved because the method from the superclass is assumed to be logically doing the same thing as the method in the subclass.
Conditions for Method Overriding
- The method must have the same name in both subclass and superclass.
- The method must have the same parameter list in both subclass and superclass.
- The return type of method can be the same or covariant (subtype) in subclass and superclass.
- If a method throws unchecked exceptions (like ArithmeticException), it can throw any unchecked exceptions, irrespective of whether its superclass method throws exceptions or not. But, if the method throws checked exceptions, it can only throw the exceptions that have been declared in the subclass method or its subclasses.
Method Overriding and Inheritance
- A method declared final cannot be overridden.
- A method declared static cannot be overridden but can be re-declared.
- It is used to provide the specific implementation of the method that has been declared by one of its superclass.
- It is used for runtime polymorphism.
- It is performed within two classes using inheritance relation.
Access and Visibility with Overriding
- The access level cannot be more restrictive than the overridden method’s. For example, a public method in the superclass must be public in the subclass.
- If the superclass method is declared public, the overriding method in the subclass must not be either private or protected.
- If the superclass method is declared protected, the overriding method in the subclass must not be private.
Usage of the super
keyword
- The
super
keyword can be used in the subclass method to call the superclass’s overridden method. - This is useful if the subclass wants to add to, rather than replace, the superclass’s version of the method.