Here is the code to implement the scenario described
Source Code..
package area;
//@author Java_Programs
public class Area {
float area;
public static void main(String[] args) {
Area a =new Area();
a.printarea(6.7f, 8.3f);
a.printarea(5f);
}
void printarea(float length , float breadth){
area = length * breadth;
System.out.println("Area of rectangle is: " +area);
}
void printarea(float side){
area = side * side;
System.out.println("Area of square is: "+area);
}
}
The above code is demonstrates the concept of method
overloading. It defines a class named "Area" that contains two
methods with the same name "printarea", but with different
parameters. The purpose of the class is to calculate the area of a rectangle and
a square based on the input parameters, and print the result to the console.
The class "Area" is defined with a float variable
named "area". This variable will be used to store the calculated
area.
The main method is the entry point of the program. In this
method, an object of the class "Area" is created, and two methods
named "printarea" are called with different parameters. The first
method is called with two float values representing the length and breadth of a
rectangle, and the second method is called with a single float value
representing the side of a square.
The class contains two methods with the same name
"printarea", but with different parameters. The first method takes
two float parameters representing the length and breadth of a rectangle, and
calculates the area by multiplying them. The second method takes a single float
parameter representing the side of a square, and calculates the area by
squaring it. Both methods store the calculated area in the variable
"area", and print the result to the console.
When the program is executed, it will print the calculated
area of the rectangle and square to the console as follows:
Area of rectangle is: 55.61
Area of square is: 25.0
this Java program demonstrates how method overloading can be
used to define multiple methods with the same name but with different parameters,
allowing for more flexible and reusable code. The methods in the
"Area" class use this concept to calculate the area of a rectangle
and a square, and print the result to the console.
No comments:
Post a Comment