Home » Core Java » MethodOverriding in Java

MethodOverriding in Java

 

What is methodOverriding ::

  1. Method overriding is a feature in java which is used to  provide specific implementation of a method in sub class that is already provided by its super class.
  2. Runtime polymorphism is achieved by method overriding.

Rules for method overriding:
1 : Method signature must be same including return type, number of method parameters, type of parameters and order of parameters.
2 : The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass.

You can think of another example where a super class method has return type as List and sub class can have same method with sub type of List i.e. ArrayList as return type.
3. Overriding method can not throw higher Exception than original or overridden method. means if original method throws IOException than overriding method can not throw super class of IOException e.g. Exception but it can throw any sub class of IOException or simply does not throw any Exception. This rule only applies to checked Exception in Java, overridden method can throw any unchecked Exception.
4.The access level cannot be more restrictive than the overridden method’s access level. For example: if the superclass method is declared public then the overridding method in the sub class cannot be either private or protected or default.
5. Final method can not be overridden.
6. Static method can not be overridden.A static method can be called without creating instance of class.It is loaded at compile time.While overriding is a run time polymorphism concept.
7. A subclass in a different package can only override the non-final methods declared public or protected.

Instance methods can be overridden only if they are inherited by the subclass.

A method declared final cannot be overridden.

A method declared static cannot be overridden but can be re-declared.

If a method cannot be inherited, then it cannot be overridden.

A subclass within the same package as the instance’s superclass can override any superclass method that is not declared private or final.

A subclass in a different package can only override the non-final methods declared public or protected.

An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.

Constructors cannot be overridden.


Leave a comment

Your email address will not be published. Required fields are marked *

14 − ten =