Comp201: Principles of Object-Oriented Programming I
Spring 2005 -- Lab 03: Java Syntax, Calendar Class, StructureBuilder    


This lab will cover:


StructureBuilder

StructureBuilder (SB) is a tool to create UML class diagrams and automatically generate Java "stub codes".  SB can also reverse engineer Java source/byte code to produce the corresponding UML diagrams.  StructureBuilder (SB) is available on Owlnet and the PCs.

In this lab, we will use SB to design a Pizza program.  Perform the following steps to create the UML diagrams shown below.  SB will generate code that reflects the class structure, but not the specific actions on any objects.   For that, after using SB, you'll edit the resulting stub code to add the rest of the code, filling in what each method should do.

  1. Start SB by clicking on the appropriate menu item in Windows.

     

  2. Prepare to create a completely new diagram:

     

     

  3. Now, make the diagram:

     

    1. In the File menu, choose New/Class, or equivalently, click on the "New Class" button.  In the left pane, a new class box should appear. In the right pane, some Java code to declare the new class should appear.  Both will use a default class name (e.g., Class_0).

      Note:  StructureBuilder creates Full Java language level code.

      We need to edit this new class. Double-click on the class diagram, or equivalently, right-click and choose Properties, and a Properties Dialog should appear.

       

      • Select the Classes tab. Change the class name (in the Name textbox) to Circle.  Make sure the Directory text box displays the correct directory.
      • Select the Variables tab. Add the radius field by clicking on the New button Variables list box.  By default, you will get int newVariable. Select (highlight) the int text and type over double.  Select the newVariable text, and type over _radius.  Make sure the "private" radio button is selected.

       

    2. Repeat the same process to create a class called Rectangle with width and height fields of type double.

      You may want to keep the Properties dialog open. Note that you can switch classes and create new classes from its interface also.

    3. Create an interface called IShape.
      • In the File menu, choose New/Interface, or equivalently, click on the "New Interface" button, which is located immediately to the right of the New Class button.  In the left pane, a new class box should appear.   Rename the interface as IShape.
      • To add an (abstract) method for computing the area, select the Methods tab. In the Methods list box, click the New button. By default you will get the method void newMethodName.  Change this to double getArea.  Check the "abstract" check box and the "public" radio button.  NOTE: Though interface methods are by definition public and abstract, we want to explicitly declare them public and abstract in order for SB to display them correctly  The UML class diagram for IShapeshould display the getArea() method in italic.  In UML, all abstract methods are italicized.

       

    4. Make Circle and Rectangle implement IShape by dragging the inheritance arrow (the middle one) from each subclass to IShape. You may need to drag the classes around for a more readable placement.
    5. Generate method stubs for Circle and Rectangle by right-clicking each inheritance arrow, and selecting Generate Method Stubs.  Circle and Rectangle should now each have a default stub code for the getArea() method.
    6. Add a class called Pizza.
      • Add a price field of type double.

       

    7. To make Pizza reference an IShape, select class Pizza.  In the lower far-right corner of the Pizza class diagram is an "association" symbol. Click on it and drag it to the IShape class diagram.  
      • A field (i.e. variable) called iShape is automatically generated.  Rename the field to _shape.
      • Create a Get Routine for _shape.  Rename get_shape to getShape.
      • Double-click on the link arrow, and check the aggregation check box. Aggregation simply means "has-a".  You can add the text "has-a" to the link label and "_shape" to the Role A text box.  These texts are like comments and have no effect on the code.

This UML class diagram contains classes and interfaces that are used in homework #2.


Summary of Java Syntax; Using the Calendar class

From now on, we will work with the Advanced language level.  So, run DrJava and select Language Level/Advanced.

I. Java Syntax (for Advanced Level)

A Java program consists of one or more classes/interfaces.  

Comments syntax:

// Line-oriented - comment goes to end of the current line.

/*

block-oriented

can span several lines.

*/

Class definition syntax:

[…] means optional.

[public] class class-name [inheritance-specification] {

[field-list]

[constructor-list]

[method-list]

}

In the above, class-name must be a string of one or more alpha-numeric character starting with an alphabet character.  For example, Agent007Bond is a legal class name, while 007Bond is not a legal class name.  

Java is case-sensitive, meaning it distinguishes upper cases from lower cases.  For example, agent007 is distinct from Agent007.

A Java source (i.e. code) file can have one or more classes.  However, only one class in a file can be public.  The name of the file must be identical to the name of the public class it contains.

Field list syntax:

A field list consists of zero or more field declarations of the form

[static] [final] [public | private | protected] field-type field-name [assignment];

Examples:

private int _width;

private double _radius = 5.0;

Constructor list syntax:

A constructor list consists of zero or more constructor definitions of the form

[public | private | protected]

class-name ([parameter-list]){

[statement-list;]

}

NOTE: The constructor's name is the same as the class name. Constructors are used for initialization of the object during the object's instantiation only.  If you do not define a constructor, by default the compiler will generate a "default" constructor that takes no parameters at all.  This is to make it possible for you to instantiate (by calling new on the constructor). 

The Elementary, Intermediate and Advanced Language levels of DrJava will automatically create a constructor for you that takes as many input parameters as necessary to initialize all the fields of a class.

Do not worry about the access specifiers private and protected for now.

Examples:

public Rectangle(double width, double height) {
    _width = width;
    _height = height;
}

public Nothing() {
  // no code at all!
}

 

Java Statement syntax:

NOTE: Each Java statement must terminate with a semi-colon.

 

Method list syntax:

A method list consists of zero or more method definitions of the form

[static] [final] [public | private | protected]

return-type method-name [param-list] {

[statement-list;]

}

A return type void means the method does not return any value.

param-list looks like:

type1 param1, type2 param2, …, typeN paramN

Examples:

public double get Area () {
    return _width * _height;
}

public double circleArea(double radius) {
    return Math.PI * radius * radius;
}

To call a method on an object, use the object variable's name followed by a period and then the method name with parentheses surrounding the input parameter values, if any:

aRectangleObject.getArea(); // you still need the parentheses even if there are no input parameters!
                           // That's how Java knows its a method and not a field.

aGeometryObject.circleArea(42.94); // no type identifier used! 42.94 is a double already.

Syntax Exercise:

Click here to download a zip file containing four Java source files: IFruit.dj2, Mango.dj2, Lemon.dj2, and TestFruit.dj2. These are all Advanced Level files.

Unzip the file into your lab03 directory and use DrJava to open all of them.

Try to compile all!  You will see a multitude of error messages, many of which are perhaps unintelligible.  This may appear overwhelming to the uninitiated.  One way to minimize the number of error messages is to compile one file at a time starting from the top of the hierarchy or with the file that can make sense alone and does not depend on the other files. When you are developing a program, always make sure the current file you are working on compiles before moving on to a new file.  Later, you will be taught how to use the project facility to manage programs with multiple files.

To compile a single file, right-click the filename and select "Compile Current Document".   This option is also on the main menu under "Tools".

So first, compile IFruit.dj2.  After you fix all the errors there, go on to Mango.dj2 and fix all the bugs there.  Then compile Lemon.dj2 and fix all the bugs there.  Finally compile TestFruit.dj2 and fix all the bugs there.

II. Using the Calendar Class

The purpose of this exercise is to learn how to use existing classes to perform certain useful tasks.  Basically, it entails reading the documentation, called the API, and try out calling a few methods using DrJava.  The classes we choose are Calendar and GregorianCalendar.  They will prove to be useful for homework #3.

  1. Go to the course main web page and find and click the link to the Java Resource Web Site (in the Additional Resources section).
  2. From this page find and click the link to the Java 2 API.
  3. From this page find and click the link to the class Calendar in the All Classes pane on the left hand side.  You should see the documentation for Calendar .

Calendar is an abstract class used to represent and perform common computations on date and time.  The people who develop Java have written the code to carry out most of the low-level computations, but have left a few methods "abstract" (i.e. with no code body) for the user to inherit and implement.  This way, you can re-use the existing code without having to know anything about them.  You will learn more about abstract class in the next lecture.

The Java developers also have provided us with a concrete subclass of Calendar called GregorianCalendarto represent the standard calendar that we (and most of the world) are using these days.  At the top level description of Calendar, you should see a description of direct known subclasses and the class GregorianCalendarlisted there.  Click on this link to see the documentation for GregorianCalendar.

Packages in Java:  

Packages in Java are a way to organize many different classes into manageable subsets.   Packages are set up as directories (folders).   For instance the package "java.util" is a subdirectory (subfolder) called "util" in the subdirectory "java".   Technically, in Java, the true name of a class, its "fully qualified class name", is the class name plus its package, e.g. java.util.Calendar.  We will discuss packages in more detail later.

Use  the Interactions pane of DrJava to explore the Calendar and GregorianCalendar classes.

To use the above classes, you must enter the following statement:

To instantiate a GregorianCalendar object containing today's date, enter

Now enter:

What do you see?

Enter:

Can you see what it doing?

Here is how you create a GregorianCalendar object that corresponds to March 03, 2000:

Now you can check the time, year, month and date of mar03_02 to see if it contains the information that you have wanted to record.

Try these also:

The only way you deal with a Calendar object is to call on the public methods or to access the public fields (such as Calendar.YEAR).  To paraphrase a famous quote: Ask not what you can do with an Object, ask what the Object can do for you!

You will see the use of the Calendar and GregorianCalendar class in homework #3.


Last Revised Thursday, 03-Jun-2010 09:50:10 CDT

©2005 Stephen Wong and Dung Nguyen