Tuesday 27 January 2015

Java Method Overloading

At this stage, I don’t know why you would want to do this, but Java allows method overloading. This means that you can have two or more methods with the same name:

Java > cat my_class.java
class my_class
  {
  public void multiply (int x, int y)
    {
    int a = x * y;
    System.out.println("a = " + a);
    }
  public void multiply (int x, int y, int z)
    {
    int b = x * y * z;
    System.out.println("b = " + b);
    }
  public void multiply (double x, double y)
    {
    double c = x * y;
    System.out.println("c = " + c);
    }
  }
Java > javac my_class.java
Java >

The only difference the outside world can see between these methods is in the number and type(s) of parameters they expect to receive. When you use an overloaded method, you let Java know which version to use by passing the parameters it requires:

Java > cat test_my_class.java
public class test_my_class
  {
  public static void main(String args[])
   {
    my_class my_class1 = new my_class();
    int i=2, j=3, k=4;
    double m=2.5, n=3;
    my_class1.multiply (i, j);
    my_class1.multiply (i, j, k);
    my_class1.multiply (m, n);
    }
  }
Java > javac test_my_class.java
Java > java test_my_class
a = 6
b = 24
c = 7.5
Java >