Method overloading is the practice of giving a particular method the facility to deal with multiple data types.

a Java example: suppose you defined a class called Number, with extensions Real, Complex, and Fraction. class Complex might look like:

public class Complex extends Number {

  Float real, imaginary;

  public Complex() { 
      real = 0;
      imaginary = 0;
  }

  public Complex (Float r, Float i) {
      real = r;
      imaginary = i;
  }

  public Float realpart () {
       return real;
  }

  public Float imaginarypart () {
       return imaginary;
  }

  public Number add (Real foo) {
      return new Complex (foo.toFloat() + real, imaginary);
  }

  public Number add (Fraction foo) {
      return new Complex (foo.toFloat() + real, imaginary);
  }

  public Number add (Complex foo) {
      return new Complex (foo.realpart() + real, foo.imaginarypart() + imaginary);
  }

  ...
}
in this way, the method add is overloaded to react differently depending upon its argument's class. (the constructor method Complex is also overloaded, such that it can optionally accept initial values.)

Log in or registerto write something here or to contact authors.