Download Category: - (95.34 KB)

Refer to the example code of the Circle class in Chapter 8.2, design a class named Rectangle to represent a rectangle. The class contains:

Two double data fields named width and length that specify the width and length of the rectangle. The default values are 0.0 for both width and length.
A no-arg constructor that creates a default rectangle.
A constructor that creates a rectangle with the specified width and length.
A method named getArea() that returns the area of this rectangle. A method named getPerimeter() that returns the perimeter. Accessor and Mutator methods for length and width;

Make sure that your constructors and mutator methods can check the new length and width to make sure only positive values can be used in your code, otherwise print out error message to the user.

Create your own project in Eclipse, add a test class with main method as usual first. Then add another new class called Rectangle without the main method in the same project. Now you should have two class files in your project. Implement the Rectangle class first. In your test class main method, creates two Rectangle objects—one with width 4 and length 40 and the other with width 3.5 and length 35.9. Display the width, length, area, and perimeter of each rectangle in this order.

There are two java files, one is the partial code of the Rectangle class, you still need to define the constructors with two parameters, accessor and mutator methods for data field length, and the getPerimeter() method. The second file is the partial code of the test program class, you need to create two other rectangle objects, calculate and print out the width, length, area and perimeter for each rectangle object. You can add your code to these classes.

public class Rectangle {

private double width;

// define length
private double length;

// default constructor
public Rectangle (){
width = 0.0;
// initialize length too
length = 0.0;

public double getWidth(){
return width;


public void setWidth (double newWidth)
if (newWidth > 0)
width = newWidth;
System.out.println(“Width must be positive numbers”);


public double getArea(){
return width*length;


public class TestProgramm {

* @param args
public static void main(String[] args) {
// TODO Auto-generated method stub

Rectangle r1 = new Rectangle ();

r1.setWidth(5.0);// the length is still 0, so the area is 0;

System.out.println(“the area is :” + r1.getArea());



Write a Review

Get a fresh solution of this question. Ask it now to our experts.

Ask Your Question

We have verified professionals who are ready to answer your question.


Save Time and Money

We choose experts who can quickly answer your question and that suit your budget.


Get Your Answer

Your satisfaction is 100% guaranteed. You can keep on asking questions until you get the answer you need.