Overriding Rules

  • Argument list : Must exactly match that of the overridden method. – else overload
  • Return type : Must be the same as, or a subtype of, the return type declared in the overridden method
  • Access level : Can’t be more restrictive (CAN be less restrictive) than the overridden method’s.
  • Exceptions
  • Unchecked Exceptions : CAN throw any unchecked (runtime) exception, regardless of whether the overridden method declares the exception
  • Checked Exceptions : Must NOT throw checked exceptions that are new or broader (wider) than those declared by the overridden method
  • Note that final methods cannot be overriden and you MUST override the abstract method (if the class is not an abstract)

Overloading Rules :

  • 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 exceptions.

Invoking (Overriding / Overloading)

Even though the actual object at runtime is a Horse and not an Animal, the choice of which overloaded method to call is NOT dynamically decided at runtime.
The reference type (not the object type) determines which overloaded method is invoked!

Which overridden version of the method to call (in other words, from which class in the inheritance tree) is decided at runtime based on object type, but
which overloaded version of the method to call is based on the reference type of the argument passed at compile time.
If you invoke a method passing it an Animal reference to a Horse object, the compiler knows only about the Animal, so it chooses the overloaded version of the method that takes an Animal. It does not
matter that at runtime there’s actually a Horse being passed.

eg :

class Animal { }

class Horse extends Animal { }

class UseAnimals {

 public void doStuff(Animal a) {
 System.out.println("In the Animal version");

 public void doStuff(Horse h) {
 System.out.println("In the Horse version");

 public static void main (String [] args) {

 UseAnimals ua = new UseAnimals();

 Animal animalObj = new Animal();
 Horse horseObj = new Horse();
 Animal animalRefToHorse = new Horse();





Screenshot from 2014-07-13 16:52:17