


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Method overloading in java, a feature that allows defining multiple methods with the same name but different signatures. The concept of method signatures, the importance of method overloading, and how java determines which method to call when an overloaded method is invoked. Examples are provided to illustrate the concepts.
Typology: Study notes
1 / 4
This page cannot be seen from the preview
Don't miss anything!



Programming Assignment The next programming assignment is on the course web site. It's due in 2 weeks. Method Overloading Let's say that I have a method that returns the larger value of two doubles: public double max( double a, double b ) { if ( a > b ) return a; else return b; } Now, I can use this method with 2 doubles: double first = stdin.nextDouble(); double second = stdin.nextDouble(); double larger = max( first, second ); I can also do this: int first = stdin.nextInt(); int second = stdin.nextInt(); double larger = max( first, second ); This is OK, but not really that great. I could change the last statement to be: int larger = (int) max( first, second ); This is still not so great - does a lot of unecessary work converting ints to doubles and back again. I'd really like this: int first = stdin.nextInt(); int second = stdin.nextInt(); int larger = max( first, second ); Java allows me to do this by defining a second method with the same name! public int max( int a, int b ) { if ( a > b ) return a; else return b;
This is called method overloading. Method overloading is useful when we want to have methods that do similar tasks, but need to operate on
Lab Exercise Modify the Currency class by adding the following overloaded methods: