Each task requires code to be added to the UserTest class of project Ex3_1.
The first task is to add a new User object referenced by maria, set its address, and then retrieve the result and print it out:
User maria; // another User reference to reference new User
String theEmailAddress; // another String reference for retrieved email address
maria = new User(); // new User object referenced by maria
maria.setEmailAddress("ibs27@student.life.ac.uk"); // set the address
theEmailAddress = maria.getEmailAddress(); // retrieve the address
System.out.println("The email address is " + theEmailAddress); // confirm the value
The second task is to set and get the userID instance variable of the User object referenced by maria:
String theUserID; // String reference for the retrieved user ID
maria.setUserID("W169073"); // set object's userID
theUserID = maria.getUserID(); // retrieve the userID
System.out.println("The user ID address is " + theUserID); //confirm the value
You could also retrieve and print out the userID without storing a reference to it as follows:
System.out.println("The user ID address is " + maria.getUserID());
If the suggested statements are added, the statement
User testUser = new User();
invokes a zero-argument constructor for the User class. If you examine the User class, you will see that there is no initialization of the instance variables of User (we have not invoked any setter methods in this statement), which means that default values are used to initialize a new User object. Because userID is a reference variable, its default value is null. Executing the code confirms this! You will read more about how this works later on in Unit 3.
If we attempt to invoke a method on the reference testString (in this case the length method of a String object), the program will crash.
In Task 3 we saw that testString has the value null, which means that it does not reference an object at all, and therefore cannot have any methods invoked on it. So, the attempt to invoke length on testString causes a NullPointerException.