Sams Teach Yourself C in 21 Days

(singke) #1
Working with Java Classes and Methods 731

BD5


Overloading Methods ....................................................................................


You learned on Bonus Day 1 that one of the features of object-oriented programming is
the technique of overloading. This technique lets you create two or more methods (func-
tions) that have the same name, but differ in the number and/or type of arguments. When
you call the method, Java automatically uses the correct ones based on the arguments
you pass.
To demonstrate, I created a class with three methods called sumOf, each of which returns
the sum of its arguments. One method takes two arguments, one takes three arguments,
and the other takes four arguments. This class is called Overloaded, and its code is pre-
sented in Listing B5.5. The program OverloadDemo, in Listing B5.6, demonstrates the
overloadedmethods.

LISTINGB5.5 Overloaded.java. The Overloadedclass has an overloadedmethod
1: public class Overloaded {
2:
3: public double sumOf(double v1, double v2) {
4: return v1 + v2;
5: }
6:
7: public double sumOf(double v1, double v2, double v3) {
8: return v1 + v2 + v3;
9: }
10:
11: public double sumOf(double v1, double v2, double v3, double v4) {
12: return v1 + v2 + v3 + v4;
13: }
14: }

LISTINGB5.6 OverloadDemo.java. Demonstration of the overloadedmethods in the class
Overloaded
1: import java.lang.String;
2: import java.lang.Double;
3:
4: public class OverloadDemo
5: {
6: public static void main(String args[])
7: {
8: Overloaded MyClass;
9: double d;
10:
11: MyClass = new Overloaded();

40 448201x-Bonus5 8/13/02 11:23 AM Page 731

Free download pdf