Method Overloading Part 1 Tutorial

A method signature is the method name followed by the parameter list enclosed in parenthesis. Method overloading occurs when you have multiple methods in the same class with the same name, but with different signatures. Being able to overload a method allows us to provide a single method name that will function slightly different based on the arguments specified when calling the method.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md MethodOverloadingOne
C:\Java>cd MethodOverloadingOne
C:\Java\MethodOverloadingOne>Notepad MethodOverloadingOne.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class MethodOverloadingOne {
    public static void main(String args[]) {
        Box b = new Box();
        int iResult = b.calculateVolume(5, 5, 5);
        System.out.println("Box dimensions: 5x5x5, volume = " + iResult);
        double dResult = b.calculateVolume(4.5, 5.2, 6.2);
        System.out.println("Box dimensions: 4.5x5.2x6.2, volume =  " + dResult);

        // invoke the overloaded methods without using a reference variable
        System.out.println("Box dimensions: 8x5x9, volume = " + new Box().calculateVolume(8, 5, 9));
        System.out.println("Box dimensions: 6.2x9.2x1.5, volume = " + (new Box().calculateVolume(6.2, 9.2, 1.5)));
    }
}

class Box {
    // overloaded method calculateVolume
    int calculateVolume(int length, int height, int width) {
        return (length * height * width);
    }    

    // overloaded method calculateVolume
    double calculateVolume(double length, double height, double width) { 
        return (length * height * width);
    }
}

Now switch back to the command prompt (CMD) and type in javac MethodOverloadingOne.java and press Enter.
Now type in java MethodOverloadingOne and press Enter.


C:\Java\MethodOverloadingOne>javac MethodOverloadingOne.java
C:\Java\MethodOverloadingOne>java MethodOverloadingOne
Box dimensions: 5x5x5, volume = 125
Box dimensions: 4.5x5.2x6.2, volume = 145.08
Box dimensions: 8x5x9, volume = 360
Box dimensions: 6.2x9.2x1.5, volume = 85.56


Final thoughts

In this simple example of method overloading we only have to invoke one method name and supply different arguments. If Java did not support method overloading then I would have had to create both a calculateIntVolume() method and a calculateDoubleVolume() method. You can imagine how difficult things could become if there where separate method names because of subtle differences in the data type being passed or returned. Method overloading is used everywhere in Java programming, you will want to make sure that you have a clear understanding of how it works.


Tutorials