Overriding and overloading a method

So what do we understand by these two terms.

Overriding, lets you define the same method in different ways for different object types in an hierarchy (i.e  when there is inheritance, hence we can say a subclass can override the behavior defined in the super class). The general rules to override a method are
  1. The method MUST have the same argument list.
  2. The method MUST have the same return type.
  3. The access modifier CANNOT be less restrictive
  4. The new method should not throw new and broader exceptions; it can throw less, narrower and run-time exception. If you throw broader exception; you violate the contract defined in the super class and and also you will loose the message the actual exception has to offer  
  5. Selection among overridden methods is dynamic (decision at run-time based on the object type).
In overloading,overloading lets you define the same method in different ways for different data in the class or its subclass. The general rules to overload a method are.
  1. The method MUST have different arguments (the number of arguments/type of argument can vary)
  2. The return type CAN be changed
  3. The access modifier CAN be changed
  4. The new method CAN throw different exceptions list.
  5. Selection among overloaded methods is static (made at compile time). Ex Say you have two methods print one which takes argument as Object and another print method which takes String. When the client invokes the print method with a string "Test"; then the print method which takes String will get invoked even though String extends Object, reason the decision to call the method happened at compile time. i.e  someObject. print("Test").
  • Effective Java  - Joshua Bloch.


    Popular posts from this blog

    How does HashMap work in Java

    Immutable classes

    Equals and hashcode method