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.
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).
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).
As expected, the states of both objects are identical other than that one is visible and the other is invisible.
square1:Square
square2:Square
isVisible is a variable of type boolean.
The word private is referred to as an access modifier.
Close the object inspectors.
Open the methods drop-down menu by selecting the object square1 on the object bench and right clicking.(Figure 3).
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):
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.
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).
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):
Now select the terminal window
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.
.
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):
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.
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:
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.
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.
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).
Examine the methods associated with Student (Figure 2).
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.
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).
And verify by inspecting the return object that the name has been successfully altered.
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
Add 100 credits to student1.
Invoke getCredits and observe that an integer type (int) is returned representing the 100 credits just added.
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
We have already encountered a constructor that takes two String objects as parameters:
Student(String, String)
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.
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:
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).
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).
[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).
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).
Before attempting these exercises ensure that the the contents of chapter01 that you downloaded have been copied to your working directory session01.
Exercise 1
Exercise 2
Exercies 3
Exercise 4
Exercise 5 (Advanced)
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.