Menu
Topics Index
...
`


Classes >
Siva Nookala - 14 Mar 2016
This program shows how find area's of different shapes like rectangle, square and circle and find the shape with the largest area.

Find Largest Shape
class FindLargestShape
{
    public static void main(String arg[])
    {
        Rectangle r = new Rectangle(10, 4);
        Square s = new Square(7);
        Circle c = new Circle(3.5);
        
        System.out.println("Rectangle Area : " + r.getArea());
        System.out.println("Square Area : " + s.getArea());
        System.out.println("Circle Area : " + c.getArea());
        System.out.println();
        
        if ((r.getArea() > c.getArea()) && (r.getArea() > s.getArea()))
        {
            System.out.println("Rectangle has the largest area.");
        }
        else if( s.getArea() > c.getArea() )
        {
            System.out.println("Square has the largest area.");
        }
        else
        {
            System.out.println("Circle has the largest area.");
        }    
    }
}

class Rectangle
{
    double length;
    double breadth;

    Rectangle(double length, double breadth)
    {
        this.length = length;
        this.breadth = breadth;
    }

    double getArea()
    {
        return length * breadth;
    }
}

class Square
{
    double side;

    Square(double side)
    {
        this.side = side;
    }

    double getArea()
    {
        return side * side;
    }
}

class Circle
{
    double radius;

    Circle(double radius)
    {
        this.radius = radius;
    }

    double getArea()
    {
        return (22.0/7.0) * radius * radius;
    }
}
OUTPUT

Rectangle Area : 40.0
Square Area : 49.0
Circle Area : 38.5

Square has the largest area.

DESCRIPTION

Here we have created three shape classes - Rectangle, Square and Circle. Rectangle has width and breadth, Square has side and Circle has radius as there respective member variables. All the classes have getArea() method implemented accordingly. In the main method of FindLargestShape, we have created one object for every class and compared their area's. The shape with largest area is printed. The areas of all these shapes are also printed for comparison.

THINGS TO TRY
  • In the main method of FindLargestShape, create two more shapes - one shape object of type Rectangle and one shape object of type Circle. Compare these two objects with the existing three objects and find the shape with largest area. Observe that the if-else conditions become complex when comparing the areas of five shapes.
  • Add double getPerimeter() method in all the three classes - namely Rectangle, Square and Circle. Change the main method in FindLargestShape to compare the perimeters and print the shape with largest perimeter.

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App