Next page | Contents page |

Exercise 7 - class Rectangle

1. In a new directory, ex7, write a class called Rectangle, to represent a geometrical rectangle. Its fields will be width and height, both of type float. It will have one constructor that sets the fields. It will have accessor methods ("getters") for the fields, plus two other methods:

	public float area ()
	public float perimeter ()

A really important thing to appreciate here is that these methods need no parameters: each object of type Rectangle knows its own width and height.

Also realise that we really do mean that class names can be used as data types. They are fundamentally different from the 8 primitive data types because those did not involve objects, only values. When you construct an object of type Rectangle and assign it to a variable, the data type for that variable must be Rectangle.

2. Also write a main method in class Rectangle, for use as a test harness. It should instantiate some rectangles, call their methods, and compare the results with expected values, putting out error messages if the values are wrong. This is a possible approach to unit testing: provide a main method in every class. However, it means you would distribute a lot of test code with each finished application which is probably not desirable. We will see later that there is a free Java API called JUnit that is used by just about everyone for unit testing. Instead of using main methods it requires a separate test class corresponding to each class under test.

Next page | Contents page |