Sunday, 9 June 2013

Overloading vs Overriding

Java permits a class to replace (or override) a method that it has it has inherited. A subclass can define a method with the SAME signature as a superclass method.


Two methods have the same name but DIFFERENT signatures -- the parameter types and/or number of parameters are different.
  1. public StringBuilder append (int a);
  2. public StringBuilder append (String s);
  3. public StringBuilder append (int a, int b);


A method in the subclass has the SAME signature as a method in the superclass.
Calling An Overridden Method Within a subclass definition, you can call the superclass method with the “super” reference.
  1. public class HourlyWorker extends Employee {
  2. public String toString()
  3. {
  4. //explicitly calls Employee’s toString method return super.toString() + “Hours: “ + hours + “ Rate: “ + rate;
  6. }
  7. }