Rules – Method Overriding and Method Overloading

Overridden Methods


Any time you have a class that inherits a method from a superclass, you have the opportunity to override the method. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type. Overriding implies that you’re re-implementing a method you inherited.

The rules for overriding a method are as follows:


  • The argument list must exactly match that of the overridden me If they don’t match, you can end up with an overloaded method you didn’t intend.

  • The return type must be the same as, or a subtype of, the return type declared in the original overridden method in the superclass.

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

  • The access level CAN be less restrictive than that of the overridden method.

  • Instance methods can be overridden only if they are inherited by the subcla A subclass within the same package as the instance’s superclass can override any superclass 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).

  • The overriding method CAN throw any unchecked (runtime) exception, regardless of whether the overridden method declares the exception.

  • The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden me For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non- runtime exception unless it’s a subclass of FileNotFoundException.

  • The overriding method can throw narrower or fewer exceptions.

  • You cannot override a method marked final.

  • You cannot override a method marked static. Method marked as static is not overrid


Overloaded Methods


Overloaded methods let you reuse the same method name in a class, but with different arguments.

The rules are simple:

  • Overloaded methods MUST change the argument list.

  • Overloaded methods CAN change the return type.

  • Overloaded methods CAN change the access modifier.

  • Overloaded methods CAN declare new or broader checked exception

  • A method can be overloaded in the same class or in a subclass.

Leave a Reply

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