This example shows how to find a rectangle's area and perimeter.
Find Rectangle Area And Perimeter class FindRectangleArea { public static void main(String arg[]) { Rectangle rect = new Rectangle(10, 5); System.out.println("Length = " + rect.length); System.out.println("Breadth = " + rect.breadth); System.out.println("Area = " + rect.getArea()); System.out.println("Perimeter = " + rect.getPerimeter()); } }
class Rectangle { double length; double breadth;
Rectangle(double length, double breadth) { this.length = length; this.breadth = breadth; }
double getArea() { return length * breadth; }
double getPerimeter() { return 2 * (length + breadth); } } OUTPUTLength = 10.0 Breadth = 5.0 Area = 50.0 Perimeter = 30.0 DESCRIPTIONHere we have created a Rectangle class with member variables length and breadth . We also have declared a constructor to initialize these variables. The getArea() method returns the area and getPerimeter() returns the perimeter of the rectangle. In the main method of FindRectangleArea , we have created one reference and one object of Rectangle class. The details like breadth, length, area and perimeter are also printed. THINGS TO TRY - Add two more member variables -
fencingCost and carpetCost and initialize them using constructor. i.e. passing them as parameters.
- Add one more method,
double getFencingCost() , which returns the getPerimeter() multiplied by the fencingCost
- Add one more method,
double getCarpetCost() , which returns the getArea() multiplied by the carpetCost
- Add one more method,
double getTotalCost() , which returns the sum of getFencingCost() and getCarpetCost()
- Change the
main method in FindRectangleArea , to print all the above costs
|