"Karmanyevadhikaraste ma phaleshu kadachana, Ma karma phala hetur bhurmatey sangostva akarmani."

overriding

Rules of method overriding in Java
What is method overriding in Java with Example There are few rules which needs to be followed while overriding any method in Java, failure to follow these rules result in compile time error in Java.


1) First and most important rule regarding method overriding in Java is that you can only override method in sub class. You can not override method in same class.

2) Second important rule of method overriding in Java that name and signature of method must be same in Super class and Sub class or in interface and its implementation.

3) Third rule to override method in Java is that overriding method can not reduce accessibility of overridden method in Java. For example if overridden method is public than overriding method can not be protected, private or package-private; But opposite is true overriding method can increase accessibility of method in Java, i.e. if overridden method is protected than overriding method can be protected or public.

4) Another worth noting rule of method overriding in Java is that overriding  method can not throw checked Exception which is higher in hierarchy than overridden method. Which means if overridden method throws IOException than overriding method can not 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) You can not override private, static and final method in Java. private and static method are bonded during compile time using static binding in Java  and doesn't resolve during runtime. overriding final method in Java is compile time error. Though private and static method can be hidden if you declare another method with same and signature in sub class.

6) Overridden method is called using dynamic binding in Java at runtime based upon type of Object. As shown in following example of method overloading.

7) If you are extending abstract class or implementing interface than you need to override all abstract method unless your class is not abstract. abstract method can only be used by using method overriding.

8) Always use @Override annotation while overriding method in Java. Though this is not rule but its one of the best Java coding practice to follow. From Java 6 you can use @Override annotation on method inherited from interface as well.