This exercise addresses the issue of overloaded methods.
Write a class NMax with a static method max(). To begin with, define max() so that it takes three integer arguments and returns the largest one. The signature for the method is as follows:
public static int max(int a, int b, int c)
In addition, define a main() method that will test max(). Use the method nextInt() to obtain input rather than nextDouble() from java.util.Scanner.
When you have completed defining and testing max() so that it take integer arguments, consider how we could implement a similar method for comparing doubles. One option would be create another method named maxDouble(). However, if we had lots of different types to compare, then this approach would lead to a proliferation of methods named maxInt(), maxLong(), maxDouble() and so on.
A better solution to this problem is to create overloaded methods with the same name, but different parameter types. The compiler will work out which version to call based on the types of the supplied arguments.
Note
You have already used overloading; when you call System.out.print(), you can pass objects of type String, double or int, and Java has been working out automatically which version of the print() method to call for you.
Inside your class NMax, define a second version of the method max(), which now takes arguments of type double, and returns the largest. The signature for the function should be:
public static double max(double a, double b, double c)
Congratulations! You have now defined two overloaded methods called max().
Note
You likely also need to adapt the way you ask for user input depending on which method you want to use. For one, you would have to ask for doubles and for the other, you would have to ask for integers.
An automated test has been created for this exercise: NMaxTest.java.