Answer to Question #239192 in Java | JSP | JSF for zakia kafeel

Question #239192

Write a program that defines a shape class with a constructor that gives value to width and height.

The define two sub-classes triangle and rectangle, that calculate the area of the shape with the help

of method area (). In the main, define two instance variables a triangle and a rectangle and then call

the area() method in this two instance variables.


1
Expert's answer
2021-09-19T05:51:47-0400
public class Main {
    public static void main(String[] args) {
        Shape rectangle = new Rectangle(5, 3);
        Shape triangle = new Triangle(2, 5);
        System.out.println("Area of rectangle: " +  rectangle.getArea());
        System.out.println("Area of triangle:" + triangle.getArea());
    }
}

abstract class Shape {
    private final double width;
    private final double height;

    public Shape(double width, double height) {
        this.width = width;
        this.height = height;
    }

    public double getWidth() {
        return width;
    }

    public double getHeight() {
        return height;
    }

    public abstract double getArea();
}

class Rectangle extends Shape {
    public Rectangle(double width, double height) {
        super(width, height);
    }

    @Override
    public double getArea() {
        return this.getWidth() * this.getHeight();
    }
}

class Triangle extends Shape {
    public Triangle(double width, double height) {
        super(width, height);
    }

    @Override
    public double getArea() {
        return 0.5 * (this.getWidth() * this.getHeight());
    }
}

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