Java Fundamentals  «Prev  Next»
Lesson 4Overloading methods
Objective Overload methods.

Overloading Methods in Java

Method overloading allows you to create multiple methods with the same name. To see how this works, consider a possible
hunt()
method in the Lion class you saw earlier. It is possible to provide two different versions of a hunt()method: one for general hunting and one for hunting a specific type of prey. Following is the general version in which the lion hunts prey:

void hunt() {
  // hunt some prey, lion-style
  System.out.println("Roar!!!");
}

The hunt() method for hunting a specific type of prey requires a parameter, the name of the type of prey:
void hunt(String prey) {
  // hunt some specific prey, lion-style
  System.out.println("Now I'm hunting " + prey + "...Roar!!!");
}

How Java Compiler differentiates

From the Java compiler's perspective, the only identifiable difference between the two methods is the parameter list for each. The Java compiler keeps up with both the name and parameter list of a method when it comes to identifying the method. The appropriate method is executed based on the type and number of parameters provided in a call to the method.
For example, the following code calls the generic hunt() method:

myLion.hunt();

Likewise, the following code calls the new overloaded hunt() method:
myLion.hunt("wildebeest");

Overloading Methods - Exercise

In this exercise, you will overload a method and develop a test program.
Overloading Methods - Exercise