Method Overloading

Each variable needs to have its own unique name. But this is not true for methods. Methods can have the same name. This is a technique called method overloading, and sometimes there is a good reason for doing so.

Let’s look at a simple example:

public class MyMethod {

  static void whatType(byte value) {
    System.out.println(value);
    System.out.println("This is a byte.");
  }

  static void whatType(int value) {
    System.out.println(value);
    System.out.println("This is an int.");
  }

  static void whatType(double value) {
    System.out.println(value);
    System.out.println("This is a double.");
  }

  static void whatType(char value) {
    System.out.println(value);
    System.out.println("This is a char.");
  }

  public static void main(String[] args) {

    byte myByte = 3;

    whatType(myByte);
    whatType(100);
    whatType(5.4);
    whatType('A');

  }
}

In this example, I have made four methods. Each one is named ‘whatType.’ But notice that each one has a different parameter list. You are allowed to give your methods the same name as long as each one has a different parameter list.

Down in the main part of this program, I made four calls to a method named ‘whatType,’ but supplied a different argument type each time. Java looks at the argument type, then finds which method to use based on which parameter list matches the supplied arguments. So the output looks like:

3
This is a byte.
100
This is an int.
5.4
This is a double.
A
This is a char.

Experiment:

Let’s have a little fun with Java.

We know from an earlier lesson that if we call a method and supply a smaller argument type than the method is expecting, that an automatic type cast will occur. So what will happen if we deliberately make a method call with an argument type that could be cast up to match more than one method?

This will be awesome! Let’s see:

public class MyMethod {

  static void whatType(double value) {
    System.out.println("double wins!");
  }

  static void whatType(long value) {
    System.out.println("long wins!");
  }

  static void whatType(float value) {
    System.out.println("float wins!");
  }

  static void whatType(short value) {
    System.out.println("short wins!");
  }

  public static void main(String[] args) {

    byte myByte = 3;
    whatType(myByte);

  }
}

And the output is:

short wins!

I admit I am disappointed that a kerfuffle did not occur. Java simply made the call to the method that required the least amount of data upgrading.

Very cleaver Java and well played. I shall have to think twice before coming at you with that weak brew again.

Next Topic: if... else... if

Comments

Popular Posts