Implementing Rectangle Class

The Rectangle class represents a rectangle in the coordinate plane. The rectangle class will also have methods to calculate the area and perimeter of a given rectangle.

In this step, you will practice using composition and code reuse.

Creating instance variables

Create four private instance variables of type Point for the four corners of the rectangle. The Point class is used to store the x- and y-coordinates of its four corners.

The use of classes as instance variables is a design method known as composition. With composition, Rectangle becomes a user of the Point class. The Rectangle class has no special privileges with respect to Point.

private Point upperLeft, lowerLeft, lowerRight, upperRight;      

Question: Why should we use 4 Points instead of 8 ints?

Creating a Constructor

The constructor of the Rectangle class should take the coordinates of the four corners (Points) as four parameters. Assign the values of four parameters(upperLeft, lowerLeft, lowerRight and upperRight) to the corresponding instance variables. (See Lab3-Step3 on how to create constructors.)

The constructor's signature is then:

public Rectangle (Point upperLeft, Point lowerLeft, Point lowerRight, Point upperRight)
{
  // Add your code here
}     

Creating getLength( ) method

getLength() method returns the length of the rectangle. This method must use the 'distance' method in the Point class for finding the length. You will have to choose which pair of points to use to calculate the length of the rectangle.

public double getLength ()
{
   // Add your code here
}     

Creating getWidth( ) method

getWidth() returns the width of the rectangle. This method also must use the 'distance' method in the Point class for finding the width. You will have to choose which pair of points to use to calculate the width of the rectangle.

public double getWidth ()
{
  // Add your code here
}     

Creating getArea( ) method

getArea() method calculates and returns the area of the rectangle. You must reuse the getLength() and getWidth() method.

public double getArea ()
{
  // Add your code here
}     

Creating getPerimeter( ) method

getPerimeter() method calculates and returns the perimeter of the rectangle. You must reuse the getLength() and getWidth() method.

public double getPerimeter () 
{
  // Add your code here
}     

Question: Why do we use getLength() and getWidth() instead of placing the calculations inside getPerimeter() and getArea()?