5.3 Overloading methods

Previous Index Next 


Another feature of the java language is called overloading. The features allows methods with the same name to exist in a class. For this to work the methods must have different signatures. The signature of the method is determined by the number and type of parameters that it accepts.

As an example:

public class Adder
 {
   public int add(int a, int b)
    {
     return a + b;
    }

   public float add(float a, float b)
    {
     return a + b;
    }
 }
Java will determine which method to call based on the parameters passed. An overloaded method can be overridden by a subclass. For instance:
public class WierdAdder extends Adder
 {
   public int add(int a, int b)
     {
       return a*b;
     }
 }
The WierdAdder class overrides the add method that accepts ints and makes it multiply the numbers instead of adding them. It is still legal to call the add() method on the WierdAdder class passing in two float since the WierdAdder inherits the add() method that accepts two floats from the Adder class.



Sources