An example of method overloading. The program calls a function to get the square root of a number. The appropriate function (integer or double version) is executed.
SquareRoots
package squareroots;
public class SquareRoots
{
public static void main(String args[])
{
double x = 3, result = 0;
int y = 5;
result = getRoot(x);
System.out.println("\n\tSquare root of " + x + " = " + result + "\n");
System.out.println("\n\tSquare of result = " + result*result + "\n");
result = getRoot(y);
System.out.println("\n\tSquare root of " + y + " = " + result + "\n");
System.out.println("\n\tSquare of result = " + result*result + "\n");
}
private static double getRoot(int inum)
{
System.out.println("\nIn the integer version");
return Math.sqrt(inum);
}
private static double getRoot(double dnum)
{
System.out.println("\nIn the double version");
return Math.sqrt(dnum);
}
}
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.