Chapter 4: Method Overloading

Method Overloading

  • Method overloading is useful when you need to perform similar operations on different types of data.
  • The same method name with different parameter list allows for method overloading.
  • The compiler must still be able to match up each invocation with a specific method declaration. If the method name for two or more methods is the same, then additional information is used to tell which version is being invoked.
  • In Java, a method name can be used for several methods as long as the number of parameters, the types of those parameters, and/or the order of the types of parameters is different.
  • A method’s name along with the number, type, and order of its parameters is called the method’s signature.
  • The compiler uses the complete method signature to bind a method invocation to its definition.

Class work:

1. Select a class of your choice and overload the constructor and a method. Submit also a test class to demonstrate the use of both constructors.

2. What error do you get if your overloaded constructor or method has the same signature as the original constructor or method? Based on the error given, can you deduce if overloading takes place at compilation or run time?

3. Write a method called evenlyDivisible that accepts two int parameters and returns true if the first parameter can be evenly divided by the second, or vice versa, and false if it can’t be. Return false if either parameter is zero. Overload evenlyDivisible to accept Integer parameters and have the same functionality. Include any comment you feel is appropriate.

4. Write a method called average that accepts two integer parameters and returns their average as a floating-point value. Overload the average method so that the method returns the average of three integers. Overload the average method to take four integer parameters and return their average.