Class components

Here you will be introduced to Java source code and acquire practice in the use of methods and parameter passing. The state of an object will be explored. You will write code to solve simple problems related to geometric shapes such as a circle and right circular cone, for example calculating the area and perimeter of the circle and the volume of the cone.

Object state

Launch BlueJ and open the shapes project.

Create a Square object named square1 and invoke makeVisible. A red square shold appear in the BlueJ Shapes Demo window (Figure 1).

Figure 1: State of square1 object

Open the object inspector by right clicking on the Square object (the red rectangle) on the object bench and selecting Inspect, located towards the bottom of the drop-down menu.

Create a second Square object named square2 and open its object inspector (Figure 2).

Figure 2: State of square2 object

As expected, the states of both objects are identical other than that one is visible and the other is invisible.

  • square1:Square

    • private boolean isVisible : true
  • square2:Square

    • private boolean isVisible : false

isVisible is a variable of type boolean.

  • a boolean has two possible values: true or false

The word private is referred to as an access modifier.

  • We shall discuss these in detail later. Access modifiers determine who has access to variables and methods within instances of a class (objects).

Close the object inspectors.

Open the methods drop-down menu by selecting the object square1 on the object bench and right clicking.(Figure 3).

Figure 3: State methods

Let's change the state of the individual Square objects, first square1:

changeColor: black
changeSize : 100
moveHorizontal: 100
moveVertical: 100

Invoke makeVisible on square2. You should see the following in the BlueJ Shapes Demo window (Figure 4):

Figure 4: Square objects

Inspect the state of square1 and verify that this changed state is consistent with the new values you inserted as parameters in the methods used to change the state.

Figure 5: Changed state of square1 object

Check the state of square2 and verify that it is unchanged which, again as in the previous lab section, demonstrates that changing the state of a particular object of a class has no effect on other objects of the same class (based on current class designs).

Explore Java code in BlueJ Terminal

We shall now explore some Java source code using the BlueJ Terminal to record method calls.

Close, relaunch BlueJ and open the shapes project.

Launch the terminal from the BlueJ menu (Views | Show Terminal):

Figure 1: BlueJ terminal

Now select the terminal window

  • Click on it to bring it into focus
  • In the Options menu select Record method calls (Figure 2).
  • Warning: ensure that the Options menu item Clear screen at method call is not ticked.

Figure 2: Record Method calls

In the BlueJ shapes window create a new Circle object named circle1 by selecting the Circle rectangle in the BlueJ shapes window, right clicking to reveal the drop-down menu, selecing new Circle() and naming the object circle1. See Figure 3.

Figure 3: Creating new circle object on object workbench.

Execute the following statements in succession using the drop-down menu that appears on right clicking on the circle1 object in the object bench.

makeVisible();
changeColor("red");
changeSize(100);
moveHorizontal(100);
slowMoveVertical(100);
moveUp();

As you execute each statment in turn, a corresponding statement should appear in the terminal window. Here is the complete result (Figure 4):

Figure 4: Circle method calls

Here are the Java statements that were executed as a result of the actions you took:

Circle circle1 = new Circle();
circle1.makeVisible();
circle1.changeColor("red");
circle1.changeSize(100);
circle1.moveHorizontal(100);
circle1.slowMoveVertical(100);
circle1.moveUp();

Notice the differences between what was presented in the drop-down menu and what was output to the terminal window. Here is an explanation:

Instantiation

Circle circle1 = new Circle();

Here we declare an object called circle1 of type Circle and then in the same statement we invoke the new Java operator on the constructor of the Circle class. The result is instantiantion of the Circle class and the storing of the resulting Circle object in the variable or attribute circle1.

Method invocation

With the remaining statements, for example,

circle1.makeVisible();

we invoke methods on the circle1 object.

All these methods are defined in the Circle class and are, consequently, available to be invoked by instances (objects) of the Circle class.

The period (.) in the statement circle1.makeVisible(); is the dot operator.

An object (circle1), followed by a dot (.), followed by a method (makeVisible()), results in the method being invoked.

A semi-colon is required to terminate Java statements.

Explore Java code in BlueJ code bench

In this section of the lab we shall explicitly execute the following statements:

Circle circle1 = new Circle();
circle1.makeVisible();
circle1.changeColor("red");
circle1.changeSize(100);
circle1.moveHorizontal(100);
circle1.slowMoveVertical(100);
circle1.moveUp();

Executing Java statements individually

Close, relaunch BlueJ and open the shapes project.

Open the BlueJ code pad using the menu by selecting Views | Show Code Pad:

Figure 1: BlueJ code pad

The code pad appears in the BlueJ IDE window in the bottom right (Figure 2).

In the code pad type this statement, followed by pressing the return key:

Circle circle1 = new Circle();

Pressing the return key causes the statement to be executed.

The above statement will instantiate a Circle object named circle1. It will not, however, place a representation of the object in the object bench.

Now execute

circle1.makeVisible();

A blue circle should appear in the Blue Shapes Demo window.

Execute the remaining statements in succession in the code bench.

As you execute each statement in turn you should observe behaviour exactly similar to that in the previous lab section.

The final result is illustrated in Figure 2.

Figure 2: Executing statements in BlueJ Code Bench

Executing Java statements as a group

  • Close, relaunch BlueJ and open the shapes project.

  • Open the BlueJ code pad by selecting menu (Views | Show Code Pad):

  • Copy all the seven statements (listed at the top of the page) and paste into the BlueJ code bench.

  • Press return.

You should see the exact same result as in Figure 2.

Return values

Open the lab-classes project.

Close the shapes project.

Create a new Student object.

Unlike in the case of Circle, the Student constructor requires two parameters, the student name and number.

These parameters are of type String and so it is necessary to enclose the data in double quotes (Figure 1).

Figure 1: New Student

Examine the methods associated with Student (Figure 2).

Figure 2: Student class methods

Do you notice any differences between the methods of Student class and Circle class?

Invoke the method getName. The result is illustrated in Figure 3.

Figure 3: Result getName method invocation

The signature (including modifier) of the method getName is:

String getName();

Invoking getName results in an object of type String being returned or handed back to the caller of the method.

You could, for example, assign this returned data to a new local variable thus:

String studentName = student1.getName();

studentName now stores the value returned by getName().

Now change the name of the student (Figure 4).

Figure 4: Change student name

And verify by inspecting the return object that the name has been successfully altered.

Figure 5: Check return object to verify name change

A question was posed above regarding possible differences between the methods of Student and Circle. The Circle methods are illustrated in the following Figure 6. By comparing Figure 6 and Figure 2 you will notice that the return type for all of Circle's methods is void, i.e. no data is returned, whereas some of the methods in Student return values, for example

  • getCredits returns an integer (type int)
  • getName returns text (type String)

Add 100 credits to student1.

Invoke getCredits and observe that an integer type (int) is returned representing the 100 credits just added.

Figure 6: Circle class methods

Objects as parameters

We can use any valid type as a parameter.

It is legal to use both primitive values and class objects.

Examples of primitives are: - int - Example: 4, 100, 365 - float - Example: 4.5f, 100.0f - boolean - Example: true, false

Examples of class objects are

  • A String instance
    • String string1
  • A Student instance
    • Student computerScienceStudent
  • A Circle instance
    • Circle circle1

We have already encountered a constructor that takes two String objects as parameters:

Student(String, String)

Figure 1: Two String objects as parameters

Combinations of parameter types are valid. An example is the following constructor:

public Garden(int numberTrees, TreeType beech, TreeType ash, Soil clay, Climate temperate);

Clearly it will have been necessary that all the object types used here, namely Garden, TreeType, Soil and Climate will have been defined earlier and made available to the project.

Writing an accessor for Circle class

Write an accessor method to return the area of a circle object and integrate the method into project

An accessor or getter method is used to obtain the value of a variable in an object.

Mutator or setter methods are sometimes used to assign a value to a variable in an object.

We already have gained experience in the use of setter and getter methods, for example:

  • student1.getCredits()
    • this statement uses the getter method getCredits to obtain the value stored in the credits variable belonging to Student object, student1.
  • student1.addCredits(int)
    • this statement uses the setter method addCredits to assign a value to the credits variable.

Note that considerable debate surrounds the use of setters and getters as opposed to accessing the variables in question directly. We shall deal with this in more depth as the course progresses.

An accessor method

Preliminary information

[1] The area of a circle may be calculated approxmiately from the formula

double area = 3.14159*radius*radius;

    The double data type is similar to the float type in that it represents a floating point number.

    It differs, however, in that its maximum value is vastly greater than that of a float data type.

Alternatively you may use the Math library which is automatically imported into the project.

double area = Math.pow(radius, 2)*Math.PI;

[2] Converting from int to double types

The field type for diameter in the Circle class is int.

But calculations for area are performed using double.

A double type caters for a decimal point which an int does not.

You can make this conversion from int to double by an operation called casting. Here is a sample code snippet that shows a cast from int to double:

int diameter = 100;
double val = (double)diameter/11;
//val is approx 9.0909091 to 7 decimal places

Procedure

[1] Launch BlueJ, open shapes project and Save As as a project named shapes to session01 directory, a sub-directory of labs in workspaceBlueJ.

Using Finder (OSX), Windows Explorer or otherwise, check that you have adhered to the recommended directory struture and saved the project to the intended location (Figure 1).

Figure 1: Recommended directory structure

Right click on the Circle class and select Open Editor.

This will open a Java file containing the code for the Circle class (Figure 2).

Figure 2: Circle class source code extract

[2] Write the accessor getArea with the following signature (including modifier and return type):

public double getArea();

[3] When you change the Circle.java file the rectangle representing the Circle class displays hatching (Figure 3).

Figure 3: Circle requires compilation

You can compile the unit by pressing one of the Compile buttons in the BlueJ IDE window or the Circle class definition code (Figure 3).

The hatching then disappears.

[4] Write the accessor, compile it, create a new Circle object and verify that your method produces the correct answer (Figure 4).

Figure 4: Circle requires compilation

Exercises

Before attempting these exercises ensure that the the contents of chapter01 that you downloaded have been copied to your working directory session01.

Exercise 1

  • Using the modified Circle class from the earlier stages of this lab, change the diameter of a circle object.
  • Retrieve the area of this modified Circle object.
  • Check that the method you wrote earlier to calculate the area still produces correct results.

Exercise 2

  • Write a method to return the circumference of a circle object and integrate into project.
  • The method signature (including return type) could be int getCircumference().
  • Create a circle object
  • Invoke the method you have written and note the returned value, the circumference of the circle object.
  • Use the inspector to view the circle object state. Note the values (attributes). Use these values to verify the result returned by the getCircumference method.
  • Change the diameter of the circle object and retest the result returned for the length of the circumference.

Exercies 3

  • Write a method in the Triangle class to return the area of a triangle object and integrate into project.
  • The method signature (including return type) could be int getArea().
  • Create a triangle object.
  • Invoke the method you have written and note the returned value, the area of the triangle.
  • Use the inspector to view the triangle object state. Note the values (attributes). Use these values to verify the result returned by the getArea method.

Exercise 4

  • Open the lab-classes project.
  • Create an object of class LabClass to cater for 4 students.
  • Invoke the LabClass method numberOfStudents.
    • Note the returned value. Is it what you expected?
  • Create a new Student object.
  • Again, invoke numberOfStudents. Understand why the returned result has not changed.
  • Invoke the LabClass enrolStudent method and add the Student object just created as a parameter (argument).
  • Invoke the LabClass method numberOfStudents. Satisfy yourself the answer is correct.
  • Create a further 3 Student objects.
  • Enroll these 3 students. It should be possible to do so without any errors being notified.
  • Check the number of students in the lab class. Is the number correct? Does it corrrespond to the number of students enrolled?
  • Inspect the LabClass object state to verify the number of students corresponds to the number returned by the method numberOfStudents and to the number of students that you actually enrolled.
  • Invoke LabClass printList method to see a list of all the students in lab. It should be printed to the BlueJ terminal window.
  • Create a 5th student and attempt to add to LabClass. This attempt should fail because the capacity was set to 4 when the lab class was created (instantiated).
  • Write a setter (mutator) method public void setCapacity(int capacity) that will allow one to change the capacity of the object.
  • Invoke setCapacity and set capacity to 5.
  • You should now be able to add the 5th student. When you have done so inspect the state of the lab class object and satisfy yourself that the data is correct.

Exercise 5 (Advanced)

  • Create a new class called Cone to represent a right circular cone (Figure 1).

Figure 1: Right circular cone

  • The fields of the Cone class are
    • a double type representing the height
    • a Circle object representing the base
  • The constructor signature (including return type) is
public Cone(double height, Circle base);

Exercise 6

Write and test a method to calculate and return the volume of the cone.

Exercise 7

Write and test a method to calculate and return the surface area of the cone including the base.