CodeGym/Java Blog/Java Developer/Three Overriding Rules
Level 22

Three Overriding Rules

Published in the Java Developer group
New Java programmers fell puzzle in this three rules of method overriding. Lets simplify the rules. Class Parent{ (Rule 1. Access specifier ) protected (Rule 2. Return Type) Number dothework() throws (Rule 3.Exception) Exception { } } Class child extends Parent{ (1. specifier) public (2. Return Type) Integer dothework() throws (3.Exception) IOException { } } If you know how the position at (1),(2) and (3) works , your overriding concept will 100% clear. 1. Access Specifier : Child class method specifier must be higher than or equal to parent class method specifier. The order of specifier is (higher to lower) public > protected>default>private. Note that private method cannot be overrided. 2. Return Type : Now java support co-variant return type. In child method return type, it must be same or child type of its parent's method return type. When generics is used here, sometimes it make puzzle to new developer. Concept of Co-variant return type using generics must be studied and cleared. 3.Exception If child class method throws any checked exception, parents class method must throw same or parents type of that checked exception. Note that , In case of unchecked exception the rule is not application. So, you must know the type of checked and unchecked exception.
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet