Question 2 (Polymorphism)
Mathematically, the area of a rectangle is computed as length * width, the area of a circle is
computed as pi*radius*radius. Given that pi = 3.14, write a Java program with an overloaded
method called getArea() that can compute for the area of a circle or rectangle depending on the
parameters supplied. Illustrate how you will invoke the method in the main method for the two
scenarios.
import java.util.Scanner;
import static java.lang.Math.*;
class Area{
double getArea(double x, double y){
return 1;
}
double getArea(double r){
return 1;
}
}
class Rectangle extends Area{
@Override
double getArea(double x, double y) {
return x*y;
}
}
class Circle extends Area{
@Override
double getArea(double r) {
return PI*pow(r,2);
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Area areaRectangle = new Rectangle();
Area areaCircle = new Circle();
System.out.println(areaRectangle.getArea(3, 6));
System.out.println(areaCircle.getArea(8));
}
}
Comments
Leave a comment