Here is the file Rectangle.java, implementing the Rectangle class:
// Rectangle.java: model a rectangle object
public class Rectangle
{
// data fields for the object
private double myLength;
private double myWidth;
private String myName;
// constructor initializes fields from input parameters
public Rectangle(double initialLength, double initialWidth,
String initialName)
{
myLength = initialLength;
myWidth = initialWidth;
myName = initialName;
}
//accessor methods
public String toString( )
{
return "[name: " + myName + ", length: " + myLength +
", width: " + myWidth + ", area: " + getArea() +
", perimeter: " + getPerimeter() + "]";
}
public double getArea( )
{
return myLength*myWidth;
}
public double getLength( )
{
return myLength;
}
public String getName( )
{
return myName;
}
public double getPerimeter( )
{
return 2*(myLength + myWidth);
}
public double getWidth( )
{
return myWidth;
}
}
// RectangleTest.java: class with main() to test Rectangle
public class RectangleTest
{
public static void main (String[] args)
{
// Create a 3x5 rectangle called George
Rectangle aRect = new Rectangle(3, 5, "George");
System.out.println("aRect: " + aRect);
// Test the get accessor methods of Rectangle
System.out.println("The Perimeter of aRect is " +
aRect.getPerimeter());
System.out.println("The Area of aRect: " +
aRect.getArea());
System.out.println("The Length of aRect: " +
aRect.getLength());
System.out.println("The Width of aRect: " +
aRect.getLength());
System.out.println();
// Create a 5x8 rectangle called Martha
Rectangle anotherRect = new Rectangle(5, 8, "Martha");
System.out.println("anotherRect: " + anotherRect);
}
}
aRect: [name: George, length: 3.0, width: 5.0, area: 15.0, perimeter: 16.0] The Perimeter of aRect is 16.0 The Area of aRect: 15.0 The Length of aRect: 3.0 The Width of aRect: 3.0 anotherRect: [name: Martha, length: 5.0, width: 8.0, area: 40.0, perimeter: 26.0]