Monday, 24 August 2015

Method Overriding rules

Overriding is a feature that is available while using Inheritance. It is used when a class uses most of the feature of the parent class and wants to implement/modify specific functionality in certain cases.

1) We can override method in sub class and cannot override method in same class.

2) Name and signature of method must be same in Super class and Sub class or in interface and its implementation.

3) Overriding method cannot reduce accessibility of overridden method.

If overridden method is public than overriding method cannot be protected, private or package-private.

But opposite is true overriding method can increase accessibility of method, i.e. if overridden method is protected than overriding method can be protected or public.

4) Overriding method cannot throw checked Exception which is higher in hierarchy than overridden method.

If overridden method throws IOException than overriding method cannot throw java.lang.Exception in its throws clause because java.lang.Exception comes higher than IOException in Exception hierarchy.

This rule doesn't apply to RuntimeException in Java, which is not even need to be declared in throws clause in Java.

5) private, static and final method cannot be override.

private and static method are bonded during compile time using static binding and doesn't resolve during runtime.

Overriding final method is compile time error.

private and static method can be hidden if declare another method with same signature in sub class.

6) Overridden method is called using dynamic binding at runtime based upon type of Object.

7) In case, extending abstract class or implementing interface than its mandatory to override all abstract method unless class is not abstract.

8) Always use @Override annotation while overriding method (best coding practices).

From java 6 we can use @Override annotation on method inherited from interface as well.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...