A Class for Rectangles
Now we will develop another rather rudimentary classes to illustrate some of
the principles and issues we have worked with so far. This second
example relates to rectangles. We keep it simple and don't really do
any drawing. But we will get a length
from a user and compute relevant things such as the area and the
Whether you are aware of it or not, the length and width are probably the most salient measures related to a rectangle. If you know it you should be able to find out just about anything else you want about the rectangle.
So, ultimately, our rectangles will be represented by two numbers in the computer. They are not represented by a drawn rectangle. We will see this sort of pattern repeat mainly because methods are invoked using an n-tuple notation.
methodName(arg1, arg2, arg3 ... argn)
Remember, it took three numbers to represent the time, or what are often called three-tuples. One number to represent a circle, through what might be called a one-tuple. Now we will be working with two-tuples.
You should call the following file Rectangle.java and save it in its own directory. Whether or not you want to create a package is up to you. You will notice we sometimes make use of the this reference rather than referring to an instance of an object by its name.
public class Rectangle extends Object
You should compile this, likely with the more typical
We start with a discussion of the code and methods.
Now you need the following RectangleTestGUI.java to construct/instantiate a Rectangle object and work with it.
public class RectangleTestGUI extends JApplet implements ActionListener
|You do not need to specify any special path in the
You should run this code and play with the GUI some before we dig into it.
The HTML file follows and should be called RectangleTestGUI.html.
<applet code="RectangleTestGUI.class" width=300 height=200>
|If you try to click on the command button and don't have an appropriate input you should see something like the following.|
|With acceptable numbers in the length and width text fields you should see something more like the following.|
|Notice the two decimal places on the area and the
perimeter even though the inputs had more.
Now we will discuss the code.
Now we will move on to one of the classic examples for user class development, working with fractions.