You can have two methods with the same name, as long as their parameters differ in type or in number.
Java decides which one to run based on the parameter number and type.
The parameters that you call the method with match with one of the methods (they all have the same name).
This is really common in Java classes.
e.g. there are four Math.abs() methods
for different parameters. They all end up doing the same thing for different primitive data types.
int x = add(4, 5); System.out.println(x); //prints 7 double x2 = add(4.0, 5.0); //add two doubles, return an int System.out.println(x2); //prints 9 x = add(1,1,1); System.out.println(x); //prints 0 static int add (int a, int b) { return 7; //haha. I hate ints // return a+b; //the correct response } static int add (double a, double b) { return (int)(a+b); } static int add (int a, int b, int c) { return a+b-c; //just to screw things up. }
Demonstrate calculating the volume of a ball
double radius = 5.0; int radius2 = 5; double v = ballVolume (radius); int v2 = ballVolume (radius2);
So ... do we need two ballVolumes functions? Yes and no.
Do the most general one first:
public class Test { public static void main(String[] args) { double radius = 5.0; int radius2 = 5; double v = ballVolume (radius); int v2 = ballVolume (radius2); System.out.println(v); System.out.println(v2); } //this is the double version static double ballVolume(double r) { double vol = 4/3 * Math.PI * r*r*r; //pretend these are massively complex calculations return vol; } //this is the int version //only do complicated calculations in one place. Just call them from here. static int ballVolume(int r) { return (int)ballVolume( (double)r ); } }