Activity 3.1 - Experimenting with the User class
Topic
This activity allows you to experiment with objects of class User. It looks
at the creation of User objects, and how methods can be invoked on the objects
created.
Materials
In addition to the Solution document, the
project for this exercise contains:
The project also makes use of the class User defined in a separate
package, which is imported into the project.
Tasks
- Using the code in UserTest as a model, add statements to UserTest to
create another new User object referenced by maria, set its email address to
ibs27@student.life.ac.uk, retrieve the email address and print it out to
verify that the instance variable has been set as intended.
- Another part of the state of a User object is held in its instance
variable userID. There are two associated methods, setUserID and getUserID,
which allow us to make use of this variable. Using these methods, write
statements that set the user ID of the object referenced by maria to
"W169073", then retrieve the ID and print it out.
- Add the statements:
User testUser = new User();
String testString = testUser.getUserID();
System.out.println("The user ID address is " + testString);
What do you predict the output will be when these are executed, and why? Run
the project to confirm your conjecture.
- What do you think will happen if following the statements
above we add the line:
testString.length();
and then run the project?
When you have tried to complete the tasks above to your satisfaction, you can
see sample solutions in the project in the the Solution document file.
Instructions
Open the class UserTest, which contains the following sample statements:
String ema;
User ivan;
ivan = new User();
ivan.setEmailAddress("ivan@nonsuch.com");
ema = ivan.getEmailAddress();
System.out.println("The email address is " + ema);
When this code is executed, the sequence of events is as follows, line by
line.
- A string reference ema is declared.
- A variable ivan of type User is declared.
- A User object is created and ivan is made to reference it.
- The setEmailAddress method is invoked on the object, with the argument "ivan@nonsuch.com".
This causes the object to set the corresponding instance variable to the given
value.
- The getEmailAddress method is invoked on the User object. It returns the
value of the emailAddress variable of the object referenced by ivan, and
stores it in ema.
- The email address is printed out.
Based on this example, complete the tasks for this activity.
Notes
In this project we import from the package user. This will be explained later in this Unit and in Unit 5.