Oveririding rules

Rules for overriding

  • The access level can’t be more restrictive than the overridden method’s.

  •  
  • Compiles  fine

  •  
  • Not Allowed

  •  
  • Not Allowed

  •  
  • Output: :2
  • The access level CAN be less restrictive than that of the overridden method.
  • private, static and final methods can’t be overridden
  • Return type of method is never part of method signature, so only changing the return type of method does not mean overloading
  • Overriding method can not throw checked Exception higher in hierarchy than thrown by overridden method.  

  •  
  • which overridden method to call based on object type

  •  
  • Output is CHILD

  • Compiles fine










 ___________________________

In the preceding code, the test class uses an Animal reference to invoke a method on a Horse object. Remember, the compiler will allow only methods in class Animal to be invoked when using a reference to an Animal. The following will not be alllowed:
Animal c = new Horse(); c.fight(); // Can’t invoke fight(); // Animal class doesn’t have that method ****The overriding method can throw any unchecked excpetion regardless of what exception overridden method is throwing.







Leave a Reply

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