Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Activity: Writing Classes Page 1 of 10 Terminology attribute / state behavior class method header class header instance variable UML class diagram encapsulation client visibility

image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
Activity: Writing Classes Page 1 of 10 Terminology attribute / state behavior class method header class header instance variable UML class diagram encapsulation client visibility (or access) modifier accessor method mutator method calling method method declaration method invocation return statement parameters constructor Goals By the end of this activity you should be able to do the following: > Create a class with methods that accept parameters and return a value Understand the constructor and the toString method of a class Create a class with main that uses the class created above Create a jGRASP project containing all of the classes for your program Generate a UML class diagram and documentation > Create a jGRASP canvas for your program and run the program in the canvas Description In this activity, you will create two classes: one called User Info and another called User InfoDriver which contains a main method that uses the first class (i.c., UserInfoDriver creates instances of UserInfo and calls its methods). You will also create a project, UML class diagram, and canvas for the program Part 1: User Info.java - Create and test the User Info class. Create your Userinfo class and add the following comments (there will be no main method in this class). Save this class in a file named Userinfo.java as soon as you have entered the code below. Don't forget to add your Javadoc comments, the constructor and each method will need one 3 public class User Info 17 instance variables // constructor Il methods Instance variables (or fields) represent the information that an object of the class needs to store. Declare the following variables after the comment: // instance variables O firstName: a String for the user's first name o lastName: a String for the user's last name o location: a String for the user's location age: an int for the user's age status: int indicates whether the user is online or offline Hint: Use the private access modifier so that values cannot be directly accessed from outside of the object, for example, declare firstName as follows: private String first Name: Constants store values that cannot be changed. Use constants to represent the two possible statuses of the user. Constants are usually grouped with the instance variables. Page 1 of 10 Activity: Writing Classes Page 2 of 10 private static final int OFFLINE = 0, ONLINE = 1; The constructor is used in conjunction with the new operater to create an instance of User Info and initialize the fields. It should be placed right below the fields and before the methods in the class, that is right after the comment constructor in your class. The constructor does not have a return type, and it always has the same name as the class. The User Info constructor will take two parameters as input representing the first and last name of the user. The names for these parameters can be anything: however, many professional programmers use the convention of adding the suffix "Into the corresponding field name as shown below. public User Info(String first NameIn, String lastNameIn) In the constructor, store the first and last name in the appropriate instance variables: firstName = firstNamen lastName = lastNameIn; Because you do not have inputs for age, location, and status, you will need to set those to default values: location - Not specified": - age = 0; status = OFFLINE; Compile your program, click the Interactions tab, and create a new UserInfo object called and display it by entering the following in Interactions tab. User Info u new User Info("Jane", "Lane"); User Infoe 3da3da69 Note that the odd looking value (classname@hashcode), which is the object's default toString value, is not very useful. When we print or display , we usually want to see some text that tells us something about the object. In the Workbench tab, find and unfold it to see its fields. We can see that the fields in u do have the values that we set with constructor. The solution is to add a toString method to our User Info class. >(obj 420 Userinfo) Userinfo firstName- Jane(obj 409 java.lang String) private java.lang String LastName> Lane" (obj 410 java.lang String) private java.lang String location Not specified" (ab 21 java.lang String) private java.lang age private int declared in Userinfo status = 0 private int declared in Userinfo OFFLINE private final static int declared in User ONLINE=1 private final statent declared in Userno Page 2 of 10 Activity: Writing Classes Page 3 of 10 The toString method returns a String representation of the object. Create and return a local String variable called output that contains information about the User Info object. Place this method after the methods comment methods This method returns a String public String toString() { String output - Names firstName * + lastName + ": output + Locations + location + In: - output + Age: *+ age + " "; -output statusu + status; return output; After you have successfully compiled your class, click the Interactions tab, and create a new User Info object called and display it by entering the following in Interactions tab as you did above. This time, when is evaluated the toString method is implicitly invoked on w and the return value is displayed. UserInfo u - new UserInfo("Jane", "Lane"); Name: Jane Lane Location: Not specified Age: 0 Status: 0 In the example above, you can also display by entering the print statement in interactions: System.out.println(u); When the wis entered without a semi-colon, it is an expression rather than a statement. You could also enter u.toString() as an expression. Remember, in the Interactions tab, expressions are evaluated and the result is immediately displayed. Since u is an object, it "evaluates to the result of calling its toString method The methods of your class describe what your object can do the behaviors of an object) For a User Info object, we want to be able to set the location and age of the user and also to change the status. First, create a set method for location: Method does not return a value. public void set Location(String locationin) - location = location in; After compiling your class, test it in the interactions pane: User Info - new UserInfo("Jane", "Lane); u.setLocation(Auburn"); Name: Jane Lane Location: Auburn Ages o Statuss o Page 3 of 10 Activity: Writing Classes Page 4 of 10 Add a method to set the value of age. This will only change age if the age is greater than 0, and it will return a boolean value (true or false) indicating whether the age was set: public boolean setAge(int agen) - boolean isset - faser Method returns either true or false. Oil (ageIn > 0) { - age ageIn; - isset = true; return isset; Add a method to return the age (fill in the blank). Notice this method takes no parameters, but returns an int value (instead of void). public int getAge() { return Method returns an int value Finally, add a method to return the location of the user (fill in the blanks). publie - get Location() { return Add the following two methods to allow the user to log off and on: public void logort() { status OPPLINE: public void logon() { status = ONLINE: The actual values (O and I) for offline status and online status are not used in the code because they are declared as constants. This makes code easier to read and modify later. You should also hide the values when printing the class information Modify the toString method as follows to print "OMine" rather than 0 and Online rather than 1: public String toString() { - String output - NaBes firstName + + Last Name + " "; - output - Locations + location + In"; output "Ages a ge + in; output = "status ": if(status OFFLINE) If statement uses the String output = "offline": offline" or "online" rather than or 1 for status in the return else output - Online, value for the toString method. - return output; Page 4 of 10 Activity: Writing Classes Page 5 of 10 After compiling your class, test each of your methods in the interactions pane. Your output should be as follows: User Info - new UserInfo("Jane". "Lane"); Name: Jane Lane Location: Not specified Age: 0 Status: Offline u.setAge(23); .setLocation ("Auburn"); u.logon(); Names Jane Lane Locations Auburn Age: 23 Status: Online Part 2: User InfoDriver.java - Create User InfoDriver class with main method; create a project file and generate the UML class diagram for the program; create canvas for User InfoDriver and run the program in the canvas. User InfoDriver class with main - You are to create another class, UserInfoDriver, which should have a main method that creates two instances of User Info and invokes methods on these instances. In the code below two instances of User Info are created and assigned to variables user and user2 respectively. These instances are printed after they are created. Then after several methods are called on instances, the instances are printed again. Enter the code below incrementally i.e., write the skeleton code first and save it as User InfoDriver.java in the same folder as User Info). Then compile/run at strategic points to ensure that the program is correct down to that point and that you understand what each statement does. Don't forget to add your Javadoc comments e public class User InfoDriver public static void main(String[] args) { - User Info userl - new User Info Pat", "Doe) - System.out.println(" userl) userl.setLocation(Abu ) userl.setAge(19) userl. logon() System.out.println(" user) ,"Sons): User Info user2 - User Infole System.out.println("in + user2) user2.setLocation Atlanta user2.setAge(21) - User 2.logon() - System.out.println( " user2) Web-CAT - After you have created the jGRASP project in the next section, you should submit your UserInfo.java and User InfoDriver.java files to Web-CAT via the Web CAT button on the project toolbar. Page 5 of 10 Activity: Writing Classes Page 6 of 10 GRASP Project - Create ajGRASP project named User InfoDriver then add UserInfoDriver.java and UserInfo java to the project. To do this, with UserInfoDriver in the edit window, click Project > New then in the Create Project dialog enter UserInfoDriver as the Project Name, make sure the folder name is set to the folder of the source files, and click Next. You can add the two files via the dialog, or alternatively, after the project has been created, you can drag Acivity4A.java and UserInfo.java from the Browse tab file list to project User InfoDriver in the Open Projects list. UserInfoDriver {main} User Info UML class diagram - After you have created the project file and added User Info Driver.java and UserInfo.java, you should generate the UML class diagram for the project by clicking (or Project> Generate/Update UML Class Diagram). After the diagram is generated, you should see green rectangles representing the two classes. The red dashed arrow from UserInfoDriver to User Info indicates that UserInfoDriver depends on User Info If both classes are selected, deselect by clicking in the space next to the diagram. Then select a class and drag to reposition it. In your UML diagram, position the classes as they appear in the figure at right. O Project Class Othereference, etc UML Class Diagram for Project UserInfoDriver Right click on UserInfo and select "Show Class Userinfo Info" to see the class member information in the FIELDS UML Info tab. See Members for User Info in the OFFLINE: private static final figure at right below the UML class diagram. ONLINE: private static final Right-click the red dashed dependency arrow and age: private int age select "Show Dependencies Info" to see the firstName: private java.lang dependencies of between the classes in the UML Info lastName: private java.lang. tab; i.e., UserInfo Driver is using the UserInfo location: private java.lang.S constructor, and methods logOn, setAge, and status: private int status set Location in the User Info class. See figure below. CONSTRUCTORS UserinfoDriver -> Userinfo UserInfo(): public UserInfo FIELDS METHODS getAge(): public int getAgel CONSTRUCTORS getLocation(): public java.la UserInfo(): Userinfo(java.lang.String METHODS logoffo): public void logOff logon(): void logon() logon(): public void logon setAge(): boolean setAge(int) setAge(): public boolean set setLocation(): void setLocation(java setLocation(): public void se toString(: public java.lang. Dependencies in UML Info tab Members for UserInfo You can also create instances of the class by right- in UML Info tab clicking and selecting "Create New Instance which places an instance on the workbench. To invoke a method for an object on the workbench, you can right click on the object (not the class) and select "Invoke Method". Page 6 of 10 Activity: Writing Classes Page 7 of 10 GRASP Canvas - In this part of the activity, you are to create a viewer canvas for your program. This will allow you to observe the objects created in the program as method are invoked on them. The canvas works in conjunction with the debugger as well as interactions After you successfully compile your program, you have three ways to run your program in jGRASP: Run , Debug and Run in Viewer Canvas . In this part of the activity, we focus on Run in Viewer Canvas, which opens a canvas window on a new or existing canvas file. When any primitive, object, or field of an object in the Debug or Workbench tabs is dragged onto the canvas, a viewer is opened using one of several viewers associated with the variable type. Below are the basic steps for creating a canvas for your program Make sure that UserInfoDriver.java is in the edit window and that you have compiled it. Now you are ready to follow the steps below to create a viewer canvas for Activty4A. (1) On the desktop toolbar, click the Run in Canvas button . This launches the program in the debugger, stops at the first executable statement, and opens an empty canvas window (since a canvas has not yet been created for program) as shown below. File View Build Debug Project Settings Tools Window Help OXDU. public class entier puble state void mai UserDriver.main us System.out.printin g args) e ri System.out.println Usersto n e Stati Unitive 113 user.setAge(21) File Et View Ran De System.out.printl OR D Help way . U Click debug step or step-in button until you see objects and/or primitives of interest in the debug variables pane. Drag objects and primitives from the debug variables pane and elsewhere onto this canvas umma S 2 Colt Cadet Running UserInfoDriver in the canvas and stopped at the first executable statement Page 7 of 10 Activity: Writing Classes Page 8 of 10 (2) Click the Step button on the canvas window or debug tab. This creates an instance of User Info and assigns it to the variable userl. You should see aserl in the Variables tab of the Debug pane. (3) Drag user from the Debug tab onto the canvas, a default viewer should open for ser as shown below. X OBXDDDDS&U+OPERS > 3lie la terrier sertato wert erfor out.print ) sertatowser - Derintot UD 2.st.g21) File Edit View Bus Debug Help System.out.printti OH Delay sos ustam Last location a t Doe or specified se r ver Compile Messages GRASP Message ORABP Sa n g user programmas Workbench Stas running program in canvas U23 Col Code Tools After user has been dragged onto the canvas (4) Click the Step button on the canvas window or debug tab to execute next statement in UserInfoDriver. When a method is invoked on userl, you should see the respective field updated on the canvas (5) Keep stepping until you have created the second instance of Userinfo and assigned it to the variable user2. Now drag user2 onto the canvas and position it to the right of userl. Your canvas should look similar to the one below. Page 8 of 10 Activity: Writing Classes Page 9 of 10 Fede BD P Ses Tools Window Help le class for le state od s tlar for stem.out.pesa w ) 211 i Ele conview Bun Debug Help Detay .50 Fusiame firme Compte Messages GRASP Message status Status Online F r unning program in a Browse Find Debug Status: user program in canvas Line Coll Codeo Top:1 Canvas with userl and user2 (6) Save the canvas by clicking the Save button on the canvas window. (7) Now click the Step button until the program ends. After the last step in the program, you should see a status message at the bottom the canvas indicating that the run in canvas has ended. If you step one more time, the objects will be grayed out. At this time, the viewers on the canvas should be grayed out to indicate that the objects no longer exist. Now close the canvas window by clicking the close button on the upper left comer. (8) On the desktop toolbar, click the Run in Canvas button . This launches the program in the debugger, stops at the first executable statement, and opens the canvas window that you created above. Now step through the program as you did above and observe the changes in the objects and the output of program. After the last step in the program, you should see a status message at the bottom the canvas indicating that the run in canvas has ended. If you step one more time, the objects will be grayed out as before (9) Now you are going to "play" your program. On the desktop toolbar, click the Run in Canvas button . This launches the program in the debugger, stops at the first executable statement, and opens the canvas window that you created above. On the canvas, click the Play button (auto step-in) on the canvas to start the visualization. Use the Pause button and Stop button as needed. To regulate the speed of the program, decrease or increase the delay between steps using the Delay slider. Del 0 0 .30 Page 9 of 10 Activity: Writing Classes Page 10 of 10 When you play your program, you will be stepping into cach of your methods. If it is going too fast for you to see and understand what is happening at each step, then increase the delay between steps by using the Delay slider. De 0 You can also click the Pause button After you pause your program, you can step as you did above. Or if you want to step into a method at a statement that calls the method then you can click the Step-in button You can also set one or more breakpoints (right-click on the line and select Toggle Breakpoint) in any of your methods and then Resume > to the next breakpoint. The debugger will stop at the breakpoint, and you can examine the variables in the Debug tab or on the canvas. You can then step step-in . or play your program as needed. You can always stop (or end) the program, and then start it again by clicking the Run in Canvas button followed by the Play button It is important that you understand what your program is doing at cach step. Although you can observe the behavior of your program using the debugger alone, the canvas works with the debugger to provide a more conceptual visualization of your program. When you are studying the example programs provided with the class notes, you are encouraged to run these in canvas mode. After you have added the variables of interest to your canvas and saved the canvas, you should be able to play or step through the program to understand the details of its behavior. Until are able to understand the example programs, it will be difficult for you to write your own programs for the project assignments. For the User InfoDriver program above, you wrote the entire program before you created the canvas for it However, you could have created the canvas as soon as you were able to compile and ran part of the program. As you write you own programs for the project assignments, you can create a canvas as soon as there is any observable behavior. This will help you ensure that the program is correct at each increment during development. The canvas will be particularly useful when you are attempting to discover and correct errors in your program. Note that you can also use the canvas via the Debug or Workbench tabs by clicking the Open New Viewer Canvas button on the debug or workbench toolbar and then dragging one or more variables onto the canvas. Changes to these variables resulting from statements executing in the Interactions tab, from stepping the debugger, and/or from executing methods via the Invoke Method dialog will be reflected on the canvas. Usually, you will need only one canvas for your program. However, if you need more than one, you can open a new canvas window via the Debug tab drag variables onto it and save it as described above. Page 10 of 10

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Transact SQL Cookbook Help For Database Programmers

Authors: Ales Spetic, Jonathan Gennick

1st Edition

1565927567, 978-1565927568

More Books

Students also viewed these Databases questions