Answer to Question #318560 in Java | JSP | JSF for oslo

Question #318560


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.



1
Expert's answer
2022-03-26T05:46:08-0400
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));
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS