Thursday, September 25, 2014

Rules for Overriding the Method in Java

  1. The argument list must exactly same that of the overridden method. If they don't match, you can end up with an overloaded method.
  2. The return type must be the same as, or a sub-type of, the return type declared in the original overridden method in the super-class (also called co-variant return type).
  3. Instance methods can be overridden only if they are inherited by the subclass.
  4. A subclass within the same package as the instance's super-class can override any super-class method that is not marked private or final. A subclass in a different package can override only those non-final methods marked public or protected (since protected methods are inherited by the subclass).
  5. The overriding method can throw any unchecked (run-time) exception, regardless of whether the overridden method declares the exception.
  6. The overriding method must not throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-run-time exception unless it's a subclass of FileNotFoundException.
  7. You cannot override a method marked final.
  8. You cannot override a method marked static.
  9. If a class is not inherited, you cannot override its methods.