how to overload a function in java program?
Answers
Answered by
0
Use the same function name for performing multiple functions.
Example:(I’ll just write the processing part)
A program to find the area of a given figure
while(ch)//where ch is of int data type
{case 0:
{System.out.println(“Input r”);
r=sc.nextFloat();//assuming that choice “0” is for a circle
area=Area(r);
break;}
case 1:
{System.out.println(“Input a and b”);
a=sc.nextInt();
b=sc.nextInt();//assuming that choice “1” is for a square
area=Area(a,b);
break;}}
Now after all the outputting statements are written we move to the part where we write the statements for the function.
public static float Area(float r)
{float pi=3.14.
float area;
area=pi*r**r;
return area;}//for choice ‘0’.
public static int Area(int a, int b)
{int area;
area=a*b;
return area;}//for choice ‘1’.
In this program, I used the same function name for both the set of statements, this is function overloading. Hope it helps.
Example:(I’ll just write the processing part)
A program to find the area of a given figure
while(ch)//where ch is of int data type
{case 0:
{System.out.println(“Input r”);
r=sc.nextFloat();//assuming that choice “0” is for a circle
area=Area(r);
break;}
case 1:
{System.out.println(“Input a and b”);
a=sc.nextInt();
b=sc.nextInt();//assuming that choice “1” is for a square
area=Area(a,b);
break;}}
Now after all the outputting statements are written we move to the part where we write the statements for the function.
public static float Area(float r)
{float pi=3.14.
float area;
area=pi*r**r;
return area;}//for choice ‘0’.
public static int Area(int a, int b)
{int area;
area=a*b;
return area;}//for choice ‘1’.
In this program, I used the same function name for both the set of statements, this is function overloading. Hope it helps.
Answered by
0
Using overloading write a program to calculate and print the area of a square, rectangle and circle.
class AreaOverload
{
double a;
void area(int side)
{
a=side*side;
System.out.println("Area of a square is :"+a);
}
void area(int len, int br)
{
a=len*br;
System.out.println("Area of a Rectangle is :"+a);
}
void area(double r)
{
a=3.14*r*r;
System.out.println("Area of a circle is :"+a);
}
public static void main(String args[ ] )
{
AreaOverload ar=new AreaOverload();
ar.area(3);
ar.area(4,6);
ar.area(3.5);
}
}
Similar questions