Identifiers, Keywords, and Types


Objectives


Upon completion of this lab, you should be able to:



Exercise 1: Investigating Reference Assignment

In this exercise, you will investigate reference variables, object creation, and reference variable assignment.

Figure 3-1 shows a class diagram for the MyPoint class that is provided in the exercise directory. Notice that the instance variables, x and y, are both public so you can access these data members in your test program directly.  Also, the toString method is used when you print the object using the System.out.println method.

MyPoint
+ x : int
+ y : int
+ toString() : String
Figure 3-1 UML Class Diagram for the MyPoint Class

Your task is to create a test program that explores object references.

Preparation

Before you begin, make sure that you have changed directories to exercises/mod03_types/exercise1/ using the cd command in the terminal window.

cd ~/exercises/mod03_types/exercise1/

Task 1 - Creating the TestMyPoint Program

Using a text editor, create a TestMyPoint program that does the following:
  1. Declare two variables of type MyPoint and called start and end. Assign both of these variables a new MyPoint object.
  2. Set the x and y values of start to 10. Set the x value of end to 20 and the y value to 30
  3. Print out both point variables. Use code similar to:
    System.out.println("Start point is" +start);
    To make sure that you are using the MyPoint class correctly, you might want to compile and run TestMyPoint now (see "Task 2 - Compiling the TestMyPoint Program" and "Task 3 - Running the TestMyPoint Program"). If you do so, the output will look something like:

    Start point is [10,10]
    End point is [20,30]

  4. Declare a new variable of type MyPoint and call it stray. Assign stray the reference value of the existing variable end
  5. Print out stray and end.
  6. Assign new values to the x (such as 47) and y (such as 50) members of the variable stray
  7. Print out strayend and start.

Task 2 - Compiling the TestMyPoint Program

On the command line, use the <tt>javac</tt> command to compile the test program.

Task 2 - Running the TestMyPoint Program

On the command line, use the java command to run the test program.

The output should look similar to the following:

Start point is [10,10]
End point is [20,30]

Stray point is [20,30]
End point is [20,30]

Stray point is [47,50]
End point is [47,50]
Start point is [10,10]

The values reported by end reflect the change made in stray, indicating that both variables refer to the same MyPoint object. However, start has not changed, which indicates that it is independent of the other two variables.


Exercise 2: Creating Customer Accounts (Level 1, Level 2, Level 3)