...
- If you have not done it already, download the latest DrJava to your Desktop. [Use this link!|http://drjava.org.}
- Create a
lab07
directory within your Comp211 directory. - Set your DrJava "Language Level" to "Elementary"
- Create a class to calculate the areas of rectangles in DrJava by following the steps below. We will begin the process of writing a class that represents a rectangle given its width and height. We will write the class in several small steps. At each step, we will compile the code to ensure that everything is syntactically correct. By compiling the code at each small step, we hope to avoid seeing a large number of error messages that can be rather intimidating.
- In the Definitions pane (upper right pane), type the following:
Note the placement of the curly braces: the opening brace is on the same line as the class name, while the closing brace lines up with the beginning of the class definition on a new line. This is the de-facto Java coding style. This class is not very interesting because we cannot do much with it. However, it is syntactically correct and canCode Block class Rectangle { double width; double height; }
be compiled.
- Save the file in your
Comp211/lab07}}folder under the default name {{Rectangle
. he file will be saved as a.dj0
file, which is a DrJava Elementary level file.
- Click the "Compile All" button in DrJava. The file should compile with no errors.
- In the Interactions pane (bottom pane), type the following:
This code defines a variable calledCode Block Rectangle r = new Rectangle(5, 10);
r
of typeRectangle
and binds it to a new object belonging to class
Rectangle
.
- There isn't much we can do with the
Rectangel
class yet, but we can print the string representations ofRectangle
objets. In the Interactions pane, typer
and hit Enter. This action will print the string representation of object bound tocalc
. In the DrJava Elementary language level, the string representation of theRectangle
objectr
which"Rectanlge(5.,10.)"
. Conventional Java would return something much more cryptic.
- Take a look at your
Comp211/lab07
directory and you will see several new files. The compiler automatically created a file calledRectangle.class
containing the compiled code expressed as "Java bytecode" ready execution on the Java Virtual Machine (JVM). DrJava automatically generated the fileRectangle.java
which we will ignore for now.
- In the Definitions pane (upper right pane), type the following:
- Now we are ready to add to
Rectangle
a method to compute the area of a rectangle. Change the defintion of theRectangle
class to read:Code Block class Rectangle { double width; double height; double area() { return width * height; } // This line is the only change }
...