Java Programming | Function Overloading

Introduction

This is a tutorial for function overloading in java. The program uses 3 functions of same names to calculate area of circle, sqaure and rectangle. The program is extendable. Go enjoy the program. Lets begin………

Program for function overloading in java.


//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class FunctionConstArg {
//void main
public static void main (String[] args)
{
//declare float and int
float r;
int s,a,b;

//print message and take input
System.out.println("Enter Radius of circle:");
Scanner input = new Scanner(System.in);
r = input.nextFloat();

System.out.println("Enter Side of square:");
s = input.nextInt();

System.out.println("Enter length and breadth of rectangle:");
a = input.nextInt();
b = input.nextInt();

//call function and print the area
System.out.println("Area of Circle= "+area(r,3.142f));
System.out.println("Area of Square= "+area(s));
System.out.println("Area of Rectangle= "+area(a,b));
}

//declare a static functions
//circle function
public static float area(float a,float pi)
{
float ar = pi*a*a;
return ar;
}

//square function
public static int area(int a)
{
int ar = a*a;
return ar;
}

//rectangle function
public static int area(int a,int b)
{
int ar = a*b;
return ar;
}

}

Output

Enter Radius of circle:
1
Enter Side of square:
2
Enter length and breadth of rectangle:
2
6
Area of Circle= 3.142
Area of Square= 4
Area of Rectangle= 12

How does it work

  1. You enter the necessary inputs.
  2. The function calculates the area.
  3. The area is printed.

Extending it

The program can be extended by using more different shapes of geometry. You can take the necessary inputs and calculate the area of the given geometry and add there respective functions at end. Even you can do the same program to find the perimeter of different shapes.

  • Remember this is a basic part of java which can be used in any program….

Explanation.

  1. Import the Scanner.
  2. Declare the class as public
  3. Add the void main function
  4. Declare input as Scanner.
  5. Add system.out.println() function with the message to enter necessary inputs .
  6. Take the inputs and save it in variables.
  7. Add system.out.print() function to print area and call the function.
  8. Add the functions out of void main function.

At the end.

You learnt creating the Java program for Function Overloading. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Sharing options: