Вы находитесь на странице: 1из 254

Introduction to Java

for OO Developers
(Course Code JA311)
Student Exercises SDK
ERC 1.3
IBM Certified Course Material

V3.1
cover

Front cover
Student Exercises
January 2004 Edition
The information contained in this document has not been submitted to any formal IBM test and is distributed on an as is basis without
any warranty either express or implied. The use of this information or the implementation of any of these techniques is a customer
responsibility and depends on the customers ability to evaluate and integrate them into the customers operational environment. While
each item may have been reviewed by IBM for accuracy in a specific situation, there is no guarantee that the same or similar results will
result elsewhere. Customers attempting to adapt these techniques to their own environments do so at their own risk.
Copyright International Business Machines Corporation 2002, 2004. All rights reserved.
This document may not be reproduced in whole or in part without the prior written permission of IBM.
Note to U.S. Government Users Documentation related to restricted rights Use, duplication or disclosure is subject to restrictions
set forth in GSA ADP Schedule Contract with IBM Corp.
Trademarks
IBM is a registered trademark of International Business Machines Corporation.
The following are trademarks of International Business Machines Corporation in the United
States, or other countries, or both:
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the
United States, other countries, or both.
Microsoft, Windows and Windows NT are trademarks of Microsoft Corporation in the
United States, other countries, or both.
Pentium is a trademark of Intel Corporation in the United States, other countries, or both.
UNIX is a registered trademark of The Open Group in the United States and other
countries.
Linux is a registered trademark of Linus Torvalds in the United States and other countries.
Other company, product and service names may be trademarks or service marks of others.
AIX CICS ClearCase
DB2 Everyplace IMS
OS/390 Rational VisualAge
WebSphere
Introduction to Java
for OO Developers
(Course Code JA311)
Student Exercises WSAD
ERC 1.3
IBM Certified Course Material

V3.1
cover

Front cover
Student Exercises
January 2004 Edition
The information contained in this document has not been submitted to any formal IBM test and is distributed on an as is basis without
any warranty either express or implied. The use of this information or the implementation of any of these techniques is a customer
responsibility and depends on the customers ability to evaluate and integrate them into the customers operational environment. While
each item may have been reviewed by IBM for accuracy in a specific situation, there is no guarantee that the same or similar results will
result elsewhere. Customers attempting to adapt these techniques to their own environments do so at their own risk.
Copyright International Business Machines Corporation 2002, 2004. All rights reserved.
This document may not be reproduced in whole or in part without the prior written permission of IBM.
Note to U.S. Government Users Documentation related to restricted rights Use, duplication or disclosure is subject to restrictions
set forth in GSA ADP Schedule Contract with IBM Corp.
Trademarks
IBM is a registered trademark of International Business Machines Corporation.
The following are trademarks of International Business Machines Corporation in the United
States, or other countries, or both:
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the
United States, other countries, or both.
Microsoft, Windows and Windows NT are trademarks of Microsoft Corporation in the
United States, other countries, or both.
Pentium is a trademark of Intel Corporation in the United States, other countries, or both.
UNIX is a registered trademark of The Open Group in the United States and other
countries.
Linux is a registered trademark of Linus Torvalds in the United States and other countries.
Other company, product and service names may be trademarks or service marks of others.
AIX CICS ClearCase
DB2 Everyplace IMS
OS/390 Rational VisualAge
WebSphere
Student Exercises
V3.1
TOC
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Contents iii
Contents
Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v
Case Study Description. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii
Exercise 1. Hello World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1
Exercise 2. Java Language Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1
Exercise 3. Using Existing Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1
Exercise 4. Creating Your Own Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1
Exercise 5. Class Methods and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-1
Exercise 6. Object Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1
Exercise 7. Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-1
Exercise 8. Simple I/O and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-1
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
iv Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Trademarks v
V1.2.2
LSGp
Trademarks
The reader should recognize that the following terms, which appear in the content of this
training document, are official trademarks of IBM or other companies:
IBM is a registered trademark of International Business Machines Corporation.
The following are trademarks of International Business Machines Corporation in the United
States, or other countries, or both:
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the
United States, other countries, or both.
Microsoft, Windows and Windows NT are trademarks of Microsoft Corporation in the
United States, other countries, or both.
Pentium is a trademark of Intel Corporation in the United States, other countries, or both.
UNIX is a registered trademark of The Open Group in the United States and other
countries.
Linux is a registered trademark of Linus Torvalds in the United States and other countries.
Other company, product and service names may be trademarks or service marks of others.
AIX CICS ClearCase
DB2 Everyplace IMS
OS/390 Rational VisualAge
WebSphere
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
vi Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Case Study Description vii
V3.1
pref
Case Study Description
Certification Unlimited Partnership (CUP) would like to develop a Web-based application
for their Distant Exam Delivery System (DEDS). Currently CUP has many certification
exams for computing professionals to take to be CUP-certified in various fields of study.
Currently to become certified, a test taker (customer) must travel to a designated CUP
testing site and take a written, paper-based, certification test. This test must then be scored
and the results communicated back to the customer.
CUP would like DEDS to be able to allow their customers to complete their certification
exams via the Web. This system should allow people to register to become customers for
the service and allow them to update their profile. A customer would be allowed to select a
specific exam to take (after signing in to the system). Upon completion of the exam, the
results will be graded, and a score report will be delivered to the customer immediately.
Statistics on exam takers and their scores are kept for the purposes of verification,
reporting, exam effectiveness analysis, and so forth.
The generated exam will be a random collection of questions pulled from the selected tests'
pool of questions. Questions are categorized into test categories. This permits the random
generation of exams which all are representative of all major areas of coverage of a test.
Further, exam score reports provide grades on the questions within each category
(subscores) to help a candidate better understand their areas of strengths and
weaknesses.
The system needs to be built to manage customer, test and exam data. In particular,
customer data will include registration, exam transcripts and certification completion
information. Test data will include question and answer pools for both production exams
and exams under review.
Customers register with the system to specify a unique user name and password. They will
log in to take exams or to review their status (certification completion). Customers can also
obtain a transcript of previously taken exams (with scores).
Test developers should also be able to submit new tests and/or questions for review as well
as be able to perform maintenance on existing tests and questions.
CUP also needs a way for Subject Matter Experts (SMEs) to take the complete review
exam and add comments on each question.
Administration staff need to perform a series of analysis tasks including Customer analysis
(for example, demographics, progress toward certification, and so forth), Test analysis (for
example, performance measures on questions, sub score areas, and tests); test
maintenance (for example, promoting reviewed exams to production and fixing questions);
and interaction with other systems (for example, publishing reviewed exams to an external
testing service).
CUP would like this system to enhance their customer service and also integrate their
various business processes (test creation, test review, exam delivery, exam scoring,
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
viii Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
customer record management, customer analysis, test analysis, and test maintenance).
The DEDS system should also be flexible to support future business processes associated
with their certification exam business.
End of Case Study
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 1. Hello World 1-1
V3.1
EXempty
Exercise 1. Hello World
What This Exercise Is About
This exercise is intended to introduce you to Java. You may already
have a background in procedural programming. This exercise will
show you some aspects of the new language on familiar territory. You
will enter source code into a file, compile it, and execute it using the
javac.exe compiler and the java.exe virtual machine.
What You Should Be Able to Do
At the end of the lab, you should be able to:
Write Java source code using Windows Notepad as an editor
Use javac.exe to compile the source code to bytecode
Use java.exe to run the bytecode
Learning Strategy
Individual exercise
Required Materials
Sun J2SE SDK 1.4.2
Windows Notepad or equivalent
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
1-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Exercise Instructions
You have heard about the compiler and JVM. You're familiar with COBOL, PL/I or some
other procedural language. This exercise introduces you to Java by having you write,
compile, and run a short procedural Java program.
Directions
Any text editor will work for this exercise. These instructions refer to Windows Notepad
when a text editor is being referenced. You will use a text editor to write a simple Java
program. You will compile the program using the javac command from the SDK. The java
command will run the program.
Step A: Write the Source Code
1. Create directories C:\OOPwJava\lab1 if they dont already exist.
2. Create a new source file in Notepad.
a. Open Notepad by selecting Start -> Run... from the task bar.
b. Type notepad in the Open: field of the Run dialog, and click OK.
3. Create a new public class, HelloWorld, with a main method. The main method should
output the string Hello, World!.
a. Enter the following source code:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
4. Save the file as c:\OOPwJava\lab1\HelloWorld.java.
Step B: Compile the Source Code
1. Open a command window.
a. Select Start -> Run... from the task bar.
b. Type cmd in the Open: field of the Run dialog, and click OK.
2. In the new cmd window, enter the command cd c:\OOPwJava\lab1.
3. Type javac HelloWorld.java in the cmd window to compile the source code.
4. If there are any syntax errors, fix them in your HelloWorld.java source file and recompile
the program.
5. Type dir to see the files in this directory. You should see two:
a. HelloWorld.java is the source file you edited above.
b. HelloWorld.class is the byte code for the HelloWorld class.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 1. Hello World 1-3
V3.1
EXempty
Step C: Execute the Result
1. Enter java HelloWorld to execute the bytecodes of the class in a new JVM.
a. You should see the text Hello, World! displayed in the cmd window.
b. If there are any run time errors you will need to fix them, recompile, and then rerun
your program.
c. You can now close the cmd window by typing exit.
Summary
You have written, compiled, and run a simple procedural Java program using a text editor
and the SDK. Writing and executing a Hello World program is the traditional introduction
into many languages. Java is an object-oriented language. You wrote a short procedural
program, but it had to exist within a class. When you learn Java language syntax, you will
create your own classes and begin to compose object-oriented programs.
END OF LAB
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
1-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Sample Output
Hello, World!
Reference Code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
File: HelloWord.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 2. Java Language Syntax 2-1
V3.1
EXempty
Exercise 2. Java Language Syntax
What This Exercise Is About
This exercise gives you practice using the non-OO, or procedural, side
of Java. You will code all of this exercise in a single main() method of a
Driver class.
In this exercise you will also be introduced to working within the
WebSphere Studio Application Developer environment. For the
purposes of this, and future exercises, we will be using WebSphere
Studio Application Developer as a compiler, editor and execution
environment (you will no longer use the Notepad, javac and java
commands).
What You Should Be Able to Do
At the end of the lab, you should be able to:
Use some primitive data types and statements addressed in Java
Use the commonly used operators addressed in Java
Write a simple Java program
Required Materials
Individual exercise
The exercise requires WebSphere Studio Application Developer,
Version 5.1
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
2-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Exercise Instructions
Throughout this exercise (and future exercises) we will refer to WebSphere Studio
Application Developer as Application Developer. You will create an Application Developer
project for this exercise that will be reused throughout the rest of the exercises for this
course. Within that project you will create a Java package. The package is only used here
as a container used to distinguish your single driver class from other possible classes of
the same name. The directions will instruct you as to how to create the package.
You will create a Java class called Driver that will hold a single public static void
main(String[ ]) method. All of the executable code for this exercise will be put in the main()
method. The main() method will create and use an array of test scores for which some
statistics will be computed. You will create this array and code the arithmetic mean and the
standard deviation of these scores, displaying the values on the console.
You will need to create an array of doubles. The reference to the array will be called
testScores. You will access the elements in the array with a looping construct and
conditional statements. The four fundamental arithmetic operators will need to be used.
Strings and the concatenation operator will aid you in creating the display data.
Directions
Step A: Create the Project, Package, Driver Class, and Main Method
1. If WebSphere Studio Application Developer is already running, skip this step and
proceed to step 2 below. Otherwise, start up WebSphere Studio Application Developer.
a. Select the Windows Start menu and then select Programs -> IBM WebSphere
Studio -> Application Developer.
b. You may receive a dialog box requesting you enter a directory called a workspace
for the current session. Application Developer stores your work in a workspace. You
can change the workspace each time you start Application Developer, or specify a
directory and check the box in the dialog box to Use this workspace as the
default and do not show this dialog box again. If you receive this dialog box,
note the default workspace location and accept it as your workspace. If you check
the box in the dialog box, you will not see this message during startup again.
2. The default perspective used by Application Developer is determined at installation time
but can be customized at run time. If no other option is selected the default perspective
is the J2EE perspective. Most of your time this week will be in the Java perspective. If
needed, use the Preferences dialog to update your Application Developer system to
make the Java perspective the default perspective.
a. Open up the Preferences dialog by selecting menu item Window -> Preferences.
b. Expand the Workbench tree and select Perspectives.
c. Notice which entry in the Available perspectives list is the default.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 2. Java Language Syntax 2-3
V3.1
EXempty
d. If the default is not the Java perspective, select the Java perspective from the list
and click Make Default.
e. Click OK to close the Preferences dialog.
3. If needed, switch to the Java perspective. The current perspective is shown in the title
bar of Application Developer.
a. If the current perspective is not Java, select menu Window->Open Perspective->
Java. This will open up the Java perspective and switch to it.
4. From the Java perspective create a new java project with a project name of OO
Programming with Java.
a. Use the Create a Java Project toolbar button to open up the New Java Project
wizard.
b. Fill in a project name of OO Programming with Java. Use the default location for
project contents.
c. Click Finish to create the new project.
d. Notice that your Package Explorer view now contains the OO Programming with
Java project.
5. Create a new package, lab2, in the OO Programming with Java project and create a
new class Driver. This new class should extend java.lang.Object and have a main
method.
a. Select the OO Programming with Java project from the Package Explorer and
click the Create a Java Package toolbar button to open up the New Java Package
wizard. Make sure the Source Folder field is OO Programming with Java and type
in a Name value of lab2.
b. Click Finish to create the lab2 package.
c. Select package lab2 in the OO Programming with Java project from the Package
Explorer and click the Create a Java Class toolbar button to open up the New
Java Class wizard. Notice that the Source Folder and Package values have already
been filled in with the project directory and package names. Update the New Java
Class dialog to make sure the class Name is Driver, Modifiers are public, and
Superclass is java.lang.Object.
d. Also ensure that the check box labeled public static void main(String[] args) is
selected (checked). This option tells Application Developer to create a stub main
method in your new class.
e. Make sure that the Constructors from superclass check box is not selected. Since
our Driver class is just a procedural program, we do not need constructors defined
for this class.
f. Make sure that the Inherited abstract methods check box is not selected. It adds
class stubs of any abstract methods from superclasses or methods of interfaces that
need to be implemented.
g. Click Finish to have the wizard create the new Driver class in package lab2 in
project OO Programming with Java.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
2-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Step B: Create the Data
1. When you created the Driver class, the Java editor was opened on the new class in
the center of the Java perspective. The Outline view shows you the package
statement, import statements, fields, and methods that exist in your class. If you select
a field or method in the Outline view the Java editor will scroll to that method. Select
the main method in the Outline view and notice that the highlighted area in the Java
editor window is updated to indicate the scope of the main method.
Information: If the Outline view is not displayed or if it gets closed you can open it by
using the menu option Window -> Show View -> Outline.
2. Edit the main method and have it define the data that is necessary for testing. You will
need an array, testScores, that you need to initialize to a set of test score values. You
will also need an int, testCount, set to the size of the testScores array. You will need
two double variables, totalScore and meanScore. Finally, you will need an int, index.
These variables should all be defined at the top of your main method. After typing in
your code, you can right click anywhere in the Java editor and select Source ->
Format to organize your new code.
a. The main method should have been created for you when the class was created. If
the main method does not exist you can create it by typing it into the editor. The
main method should look as follows:
public static void main(String[] args) {
}
b. Select the main method and edit the main method so it defines testScores as a
reference to an array of doubles, an int testCount initialized to the length of the
testScores, totalScore and meanScore variables of type double, and an int
index.
Our solution follows:
double[] testScores = { 16.0, 22.0, 24.0, 24.0, 27.0,
28.0, 29.0, 30.0 };
int testCount = testScores.length; // number of scores
double totalScore = 0.0;
double meanScore = 0.0;
int index;
Step C: Compute and Display the Arithmetic Mean of the Scores
1. In the main method, after you have declared your variables, sum the scores stored in
the array, testScores, and then divide by the number of scores. Store the arithmetic
mean in the variable meanScore.
a. Our solution follows:
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 2. Java Language Syntax 2-5
V3.1
EXempty
// Compute the mean (arithmetic average) test score
for (index = 0; index < testCount; index++) {
totalScore = totalScore + testScores[index];
}
meanScore = totalScore / testCount;
2. Next, display the mean along with simple explanatory text. Use
System.out.println(String) to display text on the console.
a. Our solution follows:
System.out.println("The arithmetic mean is " + meanScore);
Note: The that the "+" operator is the concatenation operator for Strings.
Step D: Compute and Display the Standard Deviation of the Scores
1. As you update your main method, add your new code at the bottom of the main method
after the code you added in the steps above. For each score, compute the square of its
difference from the mean. Sum these terms in a variable. Don't worry about the sign of
the difference. The squaring operation will make all terms positive.
a. Our solution follows:
double sum = 0.0;
for (index = 0; index < testCount; index++) {
// Compute each score's difference from the mean
double distFromMean = testScores[index] - meanScore;
// Accumulate its square
double distFromMeanSquared = distFromMean * distFromMean;
sum += distFromMeanSquared;
}
2. Compute the arithmetic mean of the sum.
a. Our solution is as follows:
double meanOfSquares = sum / testCount;
3. Take the square root of the result to obtain the standard deviation. Use the
Math.sqrt(aDouble) function.
a. Our solution is as follows:
double stdDeviation = Math.sqrt(meanOfSquares);
4. Display the standard deviation along with explanatory text.
a. Our solution is as follows:
System.out.println("The standard deviation is " +
stdDeviation);
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
2-6 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
5. Save your main() method by either clicking Ctrl+s or by using the right mouse button in
the Java editor and selecting Save (it is towards the bottom of the list).
Step E: Test the Program
1. Verify that your class and method have no syntax errors.
a. Verify that the Driver class has no X in front of it. If it has a red X, something is
incorrect in the class declaration or in the main method. If there are errors they will
be displayed at the bottom of the Java perspective in the Tasks view. If you do not
see the Tasks view you can select Window -> Show View -> Tasks.
b. If you double-click an error in the Tasks view the Driver class will scroll to the line
that contains the error.
2. Run the Driver class.
a. Select the class Driver class from the Package Explorer and click the Run toolbar
button. The first time you run your Driver class the Launch Configurations dialog
will open up. Select Java Application from the Launch configurations list and
click New.
b. The Driver class should be the only class listed in the Launch Configurations
dialog. Click Run to run the Driver class. Notice that the Console view will show the
output from your application. If you double-click the title area of the Console view it
will expand to fill the entire Application Developer window. Double-click again the
Console title area to restore it to its previous size
3. Application Developer can be configured to switch over to the Debug perspective.
Select Window-> Preferences and select Debug. Verify that the Default perspective
for Run is set to Debug, then run the Driver class again.
4. You can use the shortcut bar (toward the top on the left of the main Application
Developer window) to switch between perspectives. More information about workbench
fundamentals can be found in the Navigating the workbench under Help -> Help
Contents -> Application developer information->Getting Started -> Tutorial:
Workbench basics.
Summary
Your two display statements should display the mean and standard deviation, respectively.
If you use the test score values shown in the hints in step B, you should get a mean of 25.0,
and a standard deviation of 4.2720 (your result may have more digits of output).
You used arithmetic, assignment, and concatenation operators in this exercise. You
initialized an array of literal primitive double values and then accessed the array to perform
computations on its contents. You coded two loops to carry this out. You used a Math
method and a System print method without understanding their meaning. You will learn
these things later. You placed your class in a package without understanding Java
packages. You will learn this later as well.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 2. Java Language Syntax 2-7
V3.1
EXempty
END OF LAB
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
2-8 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Reference Code:
package lab2;
public class Driver {
public static void main(String[] args) {
double[] testScores = {16.0, 22.0, 24.0, 24.0, 27.0,
28.0, 29.0, 30.0};
int testCount = testScores.length; // number of scores
double totalScore = 0.0;
double meanScore = 0.0;
int index;
for (index = 0; index < testCount; index++) {
totalScore = totalScore + testScores[index];
}
meanScore = totalScore / testCount;
System.out.println("The arithmetic mean is " + meanScore);
double sum = 0.0;
for (index = 0; index < testCount ; index++) {
// compute each score's difference from the mean
double distFromMean = testScores[index] - meanScore;
// Accumulate its square
double distFromMeanSquared = distFromMean * distFromMean;
sum += distFromMeanSquared;
}
double meanOfSquares = sum / testCount;
double stdDeviation = Math.sqrt(meanOfSquares);
System.out.println("The standard deviation is " +
stdDeviation);
}
}
Driver.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 3. Using Existing Classes 3-1
V3.1
EXempty
Exercise 3. Using Existing Classes
What This Exercise Is About
Java comes with many classes already defined. This exercise
introduces you to some of those classes. You will learn how to use
them and, by extension, other classes defined in Java.
What You Should Be Able to Do
At the end of the lab, you should be able to:
Instantiate objects
Send messages to objects
Receive return values from message sends
Use the main features of the String and Vector classes
Required Materials
WebSphere Studio Application Developer, Version 5.1
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
3-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Exercise Instructions
You will use your existing OO Programming with Java project for this exercise. Within the
project you will create a Java package called lab3.
You will create a class called Driver that will define a public static void main(String[])
method. All the executable code that you will write in this exercise will be within this main()
method.
In the scenario for this exercise you will:
Accept test statistics (corresponding name and score pairs) from the command line.
Validate number of parameters passed in.
Parse and store each parameter in a vector.
Find the high and low score.
Print the name and score pair that corresponds to the high and low scores.
Directions
Step A: Create the package, driver class, and main method
1. If WebSphere Studio Application Developer is already running, skip this step and
proceed to step 2 below. Otherwise, start up WebSphere Studio Application Developer.
a. Select the Windows Start menu and then select Programs -> IBM WebSphere
Studio -> Application Developer.
2. If needed, switch to the Java perspective. The current perspective is shown in the title
bar of Application Developer.
a. If the current perspective is not Java, select menu Window->Open Perspective ->
Java. This will open up the Java perspective and switch to it.
3. Close any old edit windows.
a. Menu File -> Close All.
4. Create a new class Driver in a new package named lab3 within the existing OO
Programming with Java project. The new Driver class needs a main method.
a. Select the OO Programming with Java project from the Package Explorer.
b. Use the Create a Java Class toolbar button to open up the New Java Class dialog.
c. Notice that the Source Folder field contains the directory for the OO Programming
with Java project.
d. Fill in a Package value of lab3. Since this package does not exist, the New Java
Class wizard will create it for you.
e. Update the New Java Class dialog to make sure the class Name is Driver, the
Modifiers are public, and Superclass is java.lang.Object.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 3. Using Existing Classes 3-3
V3.1
EXempty
f. Also ensure that the check box labeled public static void main(String[] args) is
selected. This option tells Application Developer to create a stub main method in
your new class.
g. Make sure that the Constructors from superclass check box is not selected.
h. Make sure that the Inherited abstract methods check box is not selected.
i. Click Finish to have the wizard create the new Driver class in package lab3 in
project OO Programming with Java.
Step B: Validate the command-line arguments
1. Make sure your new Driver class has a main method. If it doesnt you need to create a
new main method.
a. The main method should have been created for you in the Java editor when the
class was created. If the main method does not exist you can create it by typing it
into the Java editor. The main method should look as follows:
public static void main(String[] args) {
}
2. Update the main method. If there are no command-line arguments detected, display an
explanatory message that the arguments should be name/score pairs and then exit.
The command line arguments are passed in via the String[ ] args parameter for the
main() method.
Hint: the expression args. length evaluates to the number of arguments.
Hint: a statement of the form System.exit(int); terminates the JVM.
a. Our solution is as follows:
if (args.length == 0) {
System.out.println
("Please pass test statistics on the command line.");
System.out.println("Format: name1 score1 name2 score2 ...");
System.exit(1);
}
3. Display an explanatory message and exit if the number of command-line parameters is
odd (The parameters should be a sequence of name/score pairs.).
Hint: Using the remainder operator, %, will allow you to determine if an int is even or
odd. someInt % 2 evaluates to 0 if someInt contains an even number.
a. Our solution is as follows:
if ((args.length % 2) > 0) {
System.out.println("You must have an even number of arguments.");
System.out.println("Format: name1 score1 name2 score2 ...");
System.exit(1);
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
3-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Step C: Insert each parameter value into its corresponding instance of
java.util.Vector
1. Create a reference to a java.util.Vector. Label it names. Initialize it to be a new empty
java.util.Vector. This vector will hold the collection of names passed on the command
line.
Hint: new SomeClass() creates an instance of SomeClass using the no-argument
constructor.
a. Our solution is as follows:
java.util.Vector names = new java.util.Vector();
2. Create another reference to a java.util.Vector. Label it scores. It will hold the collection
of scores passed on the command line. The position of each score element in the
scores vector will correspond to the position of each name element in the names
vector after you populate the vectors.
a. Our solution is as follows:
java.util.Vector scores = new java.util.Vector();
3. Copy each command-line argument to its corresponding vector. That is, a name
argument should be added to the names vector, while a score argument should be
added to the scores vector.
Hint: name strings and score strings are alternating elements of the String[] args
String array parameter of main().
Hint: the add method of java.util.Vector appends an Object reference to the end of its
vector.
Hint: the expression args.length evaluates to the number of command line
parameters.
Hint: the expression index++ increments the contents of an index int variable after it is
used in an expression.
Hint: a while(expression) { } loop enters each iteration of its body only while
expression evaluates to true.
a. Our solution is as follows:
int index = 0;
while (index < args.length) {
names.add(args[index]);
index++;
scores.add(args[index]);
index++;
}
A shorter version of this loop could be coded as:
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 3. Using Existing Classes 3-5
V3.1
EXempty
int index = 0;
while (index < args.length) {
names.add(args[index++]);
scores.add(args[index++]);
}
When you use the suffix operator, as in index++, the value is evaluated first and
then incremented. The statement:
names.add(args[index++]);
has the same result as the following two statements:
names.add(args[index]);
index++;
Step D: Find the element indices of the high and low scores
1. Create int variables named hiScoreIndex and lowScoreIndex. Initialize them to 0.
These will contain the indices of the high score and low score within the vectors.
a. Our solution follows:
int hiScoreIndex = 0;
int lowScoreIndex = 0;
2. Create int variables named hiScore and lowScore. Initialize hiScore to 0. Initialize
lowScore to be the largest possible int value, Integer.MAX_VALUE.
a. Our solution follows:
int hiScore = 0;
int lowScore = Integer.MAX_VALUE;
3. Examine each element of the scores vector. Use the Integer class to access the String
value as an int value. Conditionally update hiScore or lowScore scores as you
encounter each element. Whenever you update either variable, store the current
element index in hiScoreIndex or lowScoreIndex as appropriate.
Hint: the size() method of java.util.Vector returns the number of elements stored in the
vector.
Hint: the get(int) method of java.util.Vector returns an element stored in the vector at
an int, zero-based, offset.
Hint: convert a numeric String value to an int using this form: Integer.parseInt(String);
a. Here is our solution:
for (index = 0; index < scores.size(); index++) {
//Get the score string
String scoreString = (String) scores.get(index);
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
3-6 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
//Convert scoreString to an int
int score = Integer.parseInt(scoreString);
// Accumulate index of low and high scores
if (score < lowScore) {
lowScore = score;
lowScoreIndex = index;
}
if (score > hiScore) {
hiScore = score;
hiScoreIndex = index;
}
}
Step E: Display the results
1. In your main method, after the end of the for loop you created above, add code to
display the high-scoring persons name and score. Use String concatenation to present
a meaningful sentence.
Hint: use get(int) on each vector, passing the corresponding low or high score index.
a. Our solution follows:
//Print results
System.out.println("High scorer was " + names.get(hiScoreIndex) +
" with a score of " + scores.get(hiScoreIndex));
2. Display the low-scoring persons name and score. Again use String concatenation to
present a meaningful sentence.
a. Our solution is as follows:
System.out.println("Low scorer was " + names.get(lowScoreIndex) +
" with a score of " + scores.get(lowScoreIndex));
3. Save the main() method. If the method has errors, fix the errors based on the error
messages.
Step F: Test the program
1. Run the Driver class, which will cause the JVM to execute the main() method. Pass a
series of name, score pairs on the command line. Previously we were able to just run
the main() method, this time we will have to pass parameters.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 3. Using Existing Classes 3-7
V3.1
EXempty
a. Make sure the Driver class in lab3 is selected in the Package Explorer and click
the Run dropdown menu. Select Run ...
b. This opens up the Launch Configurations dialog.
c. Verify that the Main class indicates lab3.Driver. If not, type Driver into the Main class
box and select the Search button. Select the lab3 - OO Programming with Java
package for the main type to launch.
d. Select the Arguments tab.
e. Insert name, score pairs in the Program Arguments field. Use:
Adam 18 Bob 23 Charlene 19 Doug 20 Elaine 21
f. Click Apply and then Run.
2. Check the console window for correct results. The values "Adam 18 Bob 23 Charlene
19 Doug 20 Elaine 21" should yield a display with values like these:
High scorer was Bob with a score of 23
Low scorer was Adam with a score of 18
3. Try varying parameters to test your initial test conditions. You can do this by selecting
Run -> Run... from the workbench, change the program arguments and then run your
class.
Summary
In this exercise you passed name/score test statistics on the command line. You validated
the number of parameters, and whether there was an even number of them. You extracted
the parameters from the argument array of the main method, storing each in a
corresponding java.lang.Vector instance. You examined each score to find the high and low
score index. You then used that index to display the name and score of the high and low
scoring persons. Finally you printed the name and score pair that corresponded to the high
and low scores.
You practiced using existing classes String and Vector. You used methods of the
java.lang.System class to exit the JVM and to display results. You instantiated instances of
classes, sent messages to instances, and received results. In the course of completing this
exercise you became more familiar with main features of the String, Vector, and System
classes.
END OF LAB
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
3-8 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Reference Source Code
package lab3;
public class Driver {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println
("Please pass test statistics on the command line.");
System.out.println("Format: name1 score1 name2 score2 ...");
System.exit(1);
}
if ((args.length % 2) > 0) {
System.out.println("You must have an even number of arguments.");
System.out.println("Format: name1 score1 name2 score2 ...");
System.exit(1);
}
java.util.Vector names = new java.util.Vector();
java.util.Vector scores = new java.util.Vector();
int index = 0;
while (index < args.length) {
names.add(args[index++]);
scores.add(args[index++]);
}
int hiScoreIndex = 0;
int lowScoreIndex = 0;
int hiScore = 0;
int lowScore = Integer.MAX_VALUE;
for (index = 0; index < scores.size() ; index++) {
// Get the score string
String scoreString = (String) scores.get(index);
// Convert scoreString to an int
int score = Integer.parseInt(scoreString);
if (score < lowScore) {
lowScore = score;
lowScoreIndex = index;
}
Driver.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 3. Using Existing Classes 3-9
V3.1
EXempty
if (score > hiScore) {
hiScore = score;
hiScoreIndex = index;
}
}
// Print results
System.out.println("High scorer was " + names.get(hiScoreIndex) +
" with a score of " + scores.get(hiScoreIndex));
System.out.println("Low scorer was " + names.get(lowScoreIndex) +
" with a score of " + scores.get(lowScoreIndex));
}
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
3-10 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-1
V3.1
EXempty
Exercise 4. Creating Your Own Classes
What This Exercise Is About
You will create three classes used to authenticate a customer who
wishes to access a test using the Distant Exam Delivery System
(DEDS). The UML class diagram shown below depict the classes that
you will create in this exercise.
Customer
-name : String
-eMail : String
-profile : Profile
+Customer()
+Customer(String,String)
+getEMail() : String
+getName() : String
+getProfile() : Profile
+login(String, String) : boolean
+setEmail(String) : void
+setName(String) : void
+setProfile(Profile) : void
ProfiIe
-userid : String
-password : String
+Profile() :
+Profile(String,String) :
+authenticate(String,String) : boolean
+getPassword() : String
+getUserid() : String
+setPassword(String) : void
+setUserid(String) : void
Driver
+main(String[]) : void
1
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
What You Should Be Able to Do
At the end of the lab, you should be able to:
Create your own class
Create instance variables
Create methods
Create constructors
Create accessors
Learning Strategy
Individual exercise
Required Materials
WebSphere Studio Application Developer, Version 5.1
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-3
V3.1
EXempty Exercise Instructions
You will code the appropriate constructors, methods, instance variables, and accessors for
the classes shown in the UML class diagram. The Customer class represents a customer
of DEDS. A customer has name and e-mail address attributes. It also has an associated
instance of a Profile class. A Profile has user ID and password attributes. You will code a
main method for the Driver class that will instantiate a Customer and its associated Profile
instance. You will then ask the Customer instance to log in a user having supplied user ID
and password. Finally you will display the results.
Directions
Step A: Create the package, driver class, and main method
1. If WebSphere Studio Application Developer is already running, skip this step and
proceed to step 2 below. Otherwise, start up WebSphere Studio Application Developer.
a. Select the Windows Start menu and then select Programs -> IBM WebSphere
Studio -> Application Developer.
2. If needed, switch to the Java perspective. The current perspective is shown in the title
bar of Application Developer.
a. If the current perspective is not Java, select menu Window -> Open Perspective ->
Java. This will open up the Java perspective and switch to it.
3. Close any old edit windows.
a. Menu File -> Close All.
4. Create a package named lab4 within the existing OO Programming with Java project
with the Driver class inside of it. The Driver class needs to have a main method.
a. Select the OO Programming with Java project from the Package Explorer.
b. Use the Create a Java Class toolbar button to open up the New Java Class dialog.
c. Notice that the Source Folder field contains the directory for the OO Programming
with Java project.
d. Fill in a Package value of lab4. Since this package does not exist, the New Java
Class wizard will create it for you.
e. Update the New Java Class dialog to make sure the class Name is Driver,
Modifiers are public, and Superclass is java.lang.Object.
f. Also ensure that the check box labeled public static void main(String[] args) is
selected (checked). This option tells Application Developer to create a stub main
method in your new class.
g. Make sure that the Constructors from superclass check box is not selected.
h. Make sure that the Inherited abstract methods check box is not selected.
i. Click Finish to have the wizard create the new Driver class in package lab4 in
project OO Programming with Java.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
5. You will come back and add code to the main(String[ ]) method of the Driver class in a
future step.
Information: From now on the detailed steps for creating packages and classes will be
omitted. If you need help in the future, please refer back to these detailed instructions.
Step B: Create the Customer and Profile classes
This step will create the Customer and Profile classes. They will just be empty classes (with
no fields and the default constructor) at the end of this step. You will add fields and
methods in following steps.
1. Refer to the UML class diagram to see the Customer and Profile classes.
2. Create the public Customer class within the lab4 package. Make its superclass be the
default of java.lang.Object. The only method stub option that should be selected is the
Constructors from superclass option.
Note: the detailed steps have been omitted per earlier note.
3. Create the public Profile class within the lab4 package. Make its superclass be the
default of java.lang.Object. The only method stub option that should be selected is the
Constructors from superclass option.
4. When Application Developer creates some stub methods, it may suggest what code
needs to be added using a TODO task item and an accompanying Java comment such
as // TODO Auto-generated constructor stub. The task item will appear in the Tasks
view until the comment has been deleted. The comments have been replaced with code
in all solutions from now on.
Step C: Define the fields and accessor methods
This step will define the fields (the attributes) for the Customer and Profile classes. You will
use Application Developer to generate getter and setter methods for the fields.
1. Add the private field name of type String for the Customer class. Use the Generate
Getter and Setter option of the Outline view to create getter and setter methods for the
field.
a. Edit the Customer class within package lab4.
b. In the class (after the class clause and before the constructor) create a new, private,
field name of type String. Our solution (in bold) follows:
package lab4;
public class Customer {
private String name;
/**
* Constructor for Customer
*/
public Customer () {
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-5
V3.1
EXempty
super();
}
}
c. Select the new field, name, in the Outline view and bring up a context menu ( right
click). Select Source -> Generate Getter and Setter and have Application
Developer create the getter and setter methods for the name field. Notice that in the
Generate Getter and Setter confirmation dialog box you can uncheck methods you
do not want to create. Click OK to continue. Look at the Customer.java class within
the edit window to see what Application Developer has generated for you.
Information: The methods getName() and setName(String) have been generated
for you. These are getter and setter methods that are used to retrieve the name
field's value, and set the name field's value. Note that the field name itself is marked
as private. Only methods within this class, Customer, can access this private field.
Other classes must send the getName() or setName(String) messages in order to
access this field.
2. Add the private field eMail of type String for the Customer class, and have Application
Developer generate getter and setter methods for you (repeat steps similar to 1b
through 1d).
3. Add the private field profile of type Profile for the Customer class, have Application
Developer generate getter and setter methods for you (repeat steps similar to 1b
through 1d).
4. Now edit the Profile class. Add the private field userId of type String for the Profile
class, have Application Developer generate getter and setter methods for you (repeat
steps similar to 1b through 1d(repeat steps similar to 1b through 1d): make sure you
select the Profile class).
5. Add the private field password of type String for the Profile class, have Application
Developer generate the getter and setter methods for you.
6. Note that the getter and setter methods for the eMail field in the Customer class are
getEMail and setEMail. The names of the getting and setting methods are derived from
the field name. If you use a prefix or suffix for fields (for example, fValue, _value,
val_m), you can specify the suffixes and prefixes in the Code Generation preference
page (Windows > Preferences > Java > Code Generation).
7. Save your Customer and Profile classes and fix any syntax errors you have before you
continue.
Note that any Java files that have been edited but not saved will have an asterisk (*) in
front of the file name displayed in the tab for the editor view.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-6 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Step D: Update the Driver class and test your classes
In this step, you will create an instance of the Customer class, and an instance of the
Profile class. You will then associate the profile with the customer. You will then print
information about the customer and profile to the Console window.
1. Modify the main(String[ ]) method of the Driver class in package lab4 to create an
instance of Customer and store a reference to the instance in a variable called
theCustomer.
a. Select the main(String[ ]) method of the lab4.Driver class (Note: If you do not have
a main(String[ ]) method you will have to create one).
b. Type into the main method body the Java code needed to create an instance of the
Customer class and store a reference to the instance in a variable named
theCustomer.
The code should look like:
Customer theCustomer = new Customer();
2. Send the message setName to theCustomer passing in a value of Adam. Also send
theCustomer the message setEMail with a value of adam@hotmail.com.
a. After the statement you added above, send the message setName(String) to
theCustomer passing "Adam" as the parameter.
The code should look like:
theCustomer.setName("Adam");
b. Send the message setEMail(String) to theCustomer passing
"adam@hotmail.com" as the parameter (sample code omitted).
3. Display the information (name and eMail) about theCustomer to the Console window
(using System.out.println).
a. Use System.out.println(String) to print the theCustomer's information out to the
Console window.
The code should look like:
System.out.println("The customer's name is: " +
theCustomer.getName() +
", and the eMail address is: " +
theCustomer.getEMail());
Information: Remember that white space is irrelevant, this line of code could exist all
on one line. The formatting above is done simply to make the code more readable
within this exercise.
4. Save your changes to the Driver class.
a. Save the main(String[ ]) method by clicking Ctrl+S (or selecting Save from the
pop-up menu).
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-7
V3.1
EXempty
b. There should be no syntax errors in any of the classes in the lab4 package. Fix any
syntax errors before you continue.
5. Test your code by running the Driver class.
a. Run the main(String[ ]) method by clicking Run -> Run As -> Java Application
from the menu ( or click the dropdown button next to the Runner button).
b. The Debug Perspective will open and the Console window should display the
following text:
The customer's name is: Adam, and the eMail address is:
adam@hotmail.com
6. Now update your Driver class main method to create an instance of Profile and store a
reference to the instance in a local variable called theProfile. Set the userId to ADAM
and set the password to ADAM123. Finally, display the contents of theProfile to the
output Console.
a. Switch back to the Java perspective and edit the Driver class.
b. Immediately before the System.out.println() statement in the main method, create
an instance of Profile and store its reference in a variable called theProfile.
c. Send the message setUserId(String) to theProfile passing "ADAM" as the
parameter.
d. Send the message setPassword(String) to theProfile passing "ADAM123" as the
parameter.
e. After the other System.out.println() statement, use another
System.out.println(String) statement to print the theProfile object's information out
to the Console window.
f. The code within your main(String[ ]) method for the Driver class should look like
the following:
Customer theCustomer = new Customer();
theCustomer.setName("Adam");
theCustomer.setEMail("adam@hotmail.com");
Profile theProfile = new Profile();
theProfile.setUserId("ADAM");
theProfile.setPassword("ADAM123");
System.out.println("The customer's name is: " +
theCustomer.getName() +
", and the eMail address is: " +
theCustomer.getEMail());
System.out.println("The profile's userId is: " +
theProfile.getUserId() +
", and the password is: " +
theProfile.getPassword());
7. Save your changes, fix any syntax errors and test your improved Driver class.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-8 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
a. Save the main(String[ ]) method by clicking Ctrl+S (or selecting Save from the
pop-up menu).
b. Run the main(String[ ]) method by clicking the Run toolbar button (the "runner"
picture).
c. The Console window should contain the following text:
The customer's name is: Adam, and eMail address is:
adam@hotmail.com
The profile's userId is: ADAM, and the password is: ADAM123
Step E: Associate a Profile with a Customer
In this step you will associate the instance of Profile with the instance of Customer. You will
then see how you can access the profile through the customer.
1. Modify the main(String[ ]) method in the Driver class so that after the instance of
Profile is created and initialized, the setProfile(Profile) method of Customer is called
to associate theProfile with theCustomer.
a. After the theProfile.setPassword("ADAM123"); statement send the
setProfile(Profile) message to theCustomer passing theProfile as the parameter.
Our solution looks like this:
theCustomer.setProfile(theProfile);
2. Modify the output of the theProfile's information. Rather than directly referencing the
theProfile variable, modify the code so that it accesses the instance of Profile
associated with theCustomer via the getProfile() message.
a. In the System.out.println() statement for printing theProfile's information change
"theProfile" to be "theCustomer.getProfile()".
Our solution looks like this:
System.out.println(
"The profile's userId is: " +
theCustomer.getProfile().getUserId() +
", and the password is: " +
theCustomer.getProfile().getPassword());
Information: This is called message chaining. The getProfile() message is sent to
theCustomer, the instance of Profile that is associated with theCustomer is
returned, then the message getUserId() is sent to this instance of Profile.
Functionally the two are equivalent, but with this option you no longer need to retain
a reference to the profile after it is associated with the customer.
3. Save your changes and rerun the Driver class.
a. Save the main(String[ ]) method by clicking Ctrl-s (or selecting Save from the
pop-up menu).
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-9
V3.1
EXempty
Note: How can you tell if a class has been saved or not? If changes have been
made to a class that have not been saved, the class file name (up in the tab) will
have an asterisk (*) in front of it.
b. Run the main(String[ ]) method by clicking the Run toolbar button.
c. The Console window should display the same information that was previously
displayed. If you would like to debug the code with breakpoints, you could use the
Java editor to add breakpoints by double clicking in the marker bar on the left hand
side of the line of code, and then click the bug button on the toolbar.
Step F: Create constructors for customer and profile classes
If you look at the Java code within the main(String[ ]) method of the Driver class, you have
written a lot of code to initialize the instances of Customer and Profile. You will add some
new methods to the Customer and Profile classes that will enable us to initialize the
variables without having to do it manually. These methods are called constructors.
1. Your Customer and Profile classes should already have constructors that take no
arguments. These were created for you by Application Developer when you created the
classes. Look at the Customer class and see the Customer constructor that takes no
input parameters. Note the zero-argument constructor in the Profile class as well.
2. Add a constructor to the Customer class that will take two String parameters, the name,
and the eMail (name them theName and theEMail). Initialize the name field to be the
name passed in, and the eMail field to be the eMail passed in.
a. Edit the Customer class within the package lab4.
b. Type in a new Constructor that takes the two input parameters, both of type String.
The first one is named theName and the second parameter is named theEMail.
Our solution follows:
public Customer(String theName, String theEMail) {
super();
}
c. Now update the new constructor to initialize the name and eMail fields in the
Customer class to the parameter values.
Our solution looks like (new code is in bold):
public Customer(String theName, String theEMail) {
super();
setName(theName);
setEMail(theEMail);
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-10 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
3. Add a constructor to the Profile class that will take two String parameters, the userId,
and the password (named theUserId and thePassword). Initialize the userId field to be
the userId passed in, and the password field to be the password passed in.
a. Edit the Profile class within the package lab4.
b. Add the new constructor to the Profile class that takes the two input parameters for
the user ID and the password.
Our solution looks like:
public Profile(String theUserId, String thePassword) {
super();
}
c. Update the new constructor to set the values for the user id and password fields
from the input parameters.
Our solution looks as follows (new code is in bold):
public Profile(String theUserId, String thePassword) {
super();
setUserId(theUserId);
setPassword(thePassword);
}
Step G: Modify Driver's main(string[ ]) method to use the new
constructors
In this step you will modify the main(String[ ]) to use the two constructors you created in
the previous step.
1. Modify the statement that creates the instance of Customer to use the two-argument
constructor. Remove the two set statements for name and eMail.
a. Delete the two statements that send the setName() and setEMail() messages to
theCustomer.
Our solution looks like:
Customer theCustomer = new Customer("Adam", "adam@hotmail.com");
2. Modify the statement that creates the instance of Profile to use the two argument
constructor. Remove the two "set" statements for userId and password.
a. Delete the two statements that send the setUserId() and setPassword() messages
to theProfile.
Our solution looks like:
Profile theProfile = new Profile("ADAM", "ADAM123");
3. Save your classes (Driver, Profile and Customer) and fix any syntax errors.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-11
V3.1
EXempty
4. Run the Driver class and check the Console output from the Debug perspective, it
should display the same information that was previously displayed.
Step H: Create the login and authenticate methods
So far all of our methods for the Customer and Profile classes have been dealing with
setting data, getting data or initializing data. Now you will add some actual business
functionality. You will add a login() method to Customer that will allow us to authenticate
the customer. The purpose of the Profile class is to authenticate customers (validate their
user ID and password).
1. Add the public authenticate(String, String) method to the Profile class. The first
parameter is the user ID and the second parameter is the password. This method will
have a return type of boolean.
a. Edit the Profile class within the package lab4.
b. Within the body of the Profile class enter your new authenticate method. We have
used theUserId as the name of the first parameter and have used thePassword as
the name of the second parameter.
Our solution follows:
public boolean authenticate(String theUserId, String thePassword) {
}
2. Write the source code for the authenticate(String, String) method. The method should
return true if the provided userId and password (the two parameters) match the
Profile object's user ID and password, otherwise it will return false.
a. First test to see if either of the input parameters is null. If either is you need to return
false. Next test to see if theUserId is equal to userId AND thePassword is equal to
password.
Our solution looks like:
public boolean authenticate
(String theUserId, String thePassword) {
if (theUserId == null || thePassword == null) {
return false;
}
return ( theUserId.equals(userId) &&
thePassword.equals(password) );
}
3. Add the method login(String, String) method to the Customer class. The first
parameter is the user ID to be logged in and the second parameter is the password.
This method will have a return type of boolean.
a. Edit the Customer class within the package lab4.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-12 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
b. Create a new method, login(String, String) of type public that returns back a
boolean. Our solution uses the names theUserId and thePassword for the
parameters. Our solution follows:
public boolean login(String theUserId, String thePassword) {
}
4. Write the source code for the login(String, String) method. The method should send
the message authenticate(String, String) to the customer's profile and return the
result.
a. Our solution looks like:
public boolean login(String theUserId, String thePassword) {
return profile.authenticate(theUserId, thePassword);
}
Step I: Modify Driver's main(string[ ]) method to log the customer in.
In this step you will create another customer and profile. You will log the first customer in
and verify that the login was successful. You will then log the second customer in, using an
incorrect password, and verify that the login was unsuccessful.
1. Remove the System.out.println() statements of the main(String[ ]).
2. Where the System.out.println() statements were removed, create a boolean variable
called loginSuccessful and initialize it to false.
3. Send the login(String, String) message, using the correct values, to theCustomer
and assign the result into the loginSuccessful variable.
4. Print the result out to the Console identifying the customer's name, and whether or not
the login was successful.
5. Create a new Customer assign it to a variable called anotherCustomer.
6. Create a new Profile assign it to a variable called anotherProfile.
7. Set the profile of anotherCustomer to be anotherProfile.
8. Send the login(String, String) message, using incorrect values, to anotherCustomer
and assign the result into the loginSuccessful variable.
9. Print the result to the Console identifying the customer's name, and whether or not the
login was successful.
10. Our solution to all of the above looks as follows (the complete main(String[ ]) method
text):
Customer theCustomer = new Customer("Adam", "adam@hotmail.com");
Profile theProfile = new Profile("ADAM", "ADAM123");
theCustomer.setProfile(theProfile);
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-13
V3.1
EXempty
boolean loginSuccessful = false;
loginSuccessful = theCustomer.login("ADAM", "ADAM123");
if (loginSuccessful) {
System.out.println(theCustomer.getName() +
" logged in successfully");
} else {
System.out.println(theCustomer.getName() +
" did not log in successfully");
}
Customer anotherCustomer = new Customer("Charlene",
"char@email.com");
Profile anotherProfile = new Profile("CHAR", "CHAR321");
anotherCustomer.setProfile(anotherProfile);
loginSuccessful = anotherCustomer.login("CHAR",
"WRONGPASSWORD");
if (loginSuccessful) {
System.out.println(anotherCustomer.getName() +
" logged in successfully");
} else {
System.out.println(anotherCustomer.getName() +
" did not log in successfully");
}
11. Save your classes (Driver, Profile and Customer) and fix any syntax errors.
12. Run the Driver class and check the Console output in the debug perspective and make
sure it displays the following:
Adam logged in successfully
Charlene did not log in successfully
Summary
This was an exercise in coding Java classes and their four essential ingredients:
constructors, methods, instance variables (also called fields or attributes), and access
methods (also called getters and setters, or accessors). You learned to encapsulate
instance data with accessor methods such that clients of a class could access that data
through a method call on the instance of the class. You also began to use practical Java
coding skills.
END OF LAB
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-14 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Reference Classes
package lab4;
public class Driver {
public static void main(String[] args) {
Customer theCustomer = new Customer("Adam","adam@hotmail.com");
Profile theProfile = new Profile("ADAM", "ADAM123");
theCustomer.setProfile(theProfile);
boolean loginSuccessful = false;
loginSuccessful = theCustomer.login("ADAM", "ADAM123");
if (loginSuccessful) {
System.out.println(theCustomer.getName() +
" logged in successfully");
} else {
System.out.println(theCustomer.getName() +
" did not log in successfully");
}
Customer anotherCustomer = new Customer("Charlene","char@email.com");
Profile anotherProfile = new Profile("CHAR", "CHAR321");
anotherCustomer.setProfile(anotherProfile);
loginSuccessful = anotherCustomer.login("CHAR", "WRONGPASSWORD");
if (loginSuccessful) {
System.out.println(anotherCustomer.getName() +
" logged in successfully");
} else {
System.out.println(anotherCustomer.getName() +
" did not log in successfully");
}
}
}
Driver.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-15
V3.1
EXempty
package lab4;
public class Customer {
private String name;
private String eMail;
private Profile profile;
/**
* Constructor for Customer
*/
public Customer() {
super();
}
/**
* Create a new Customer from the specified parameters
* @param theName The name to set
* @param theEMail The eMail to set
*/
public Customer(String theName, String theEMail) {
super();
setName(theName);
setEMail(theEMail);
}
/**
* Gets the name
* @return Returns a String
*/
public String getName() {
return name;
}
/**
* Sets the name
* @param name The name to set
*/
public void setName(String name) {
this.name = name;
}
/**
Customer.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-16 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
* Gets the eMail
* @return Returns a String
*/
public String getEMail() {
return eMail;
}
/**
* Sets the eMail
* @param mail The eMail to set
*/
public void setEMail(String mail) {
eMail = mail;
}
/**
* Gets the profile
* @return Returns a Profile
*/
public Profile getProfile() {
return profile;
}
/**
* Sets the profile
* @param profile The profile to set
*/
public void setProfile(Profile profile) {
this.profile = profile;
}
/**
* Log in with the specified user ID and password.
* @param theUserId User ID to use for the login request
* @param thePassword Password to use for the login request
* @return boolean True if login was a success.
*/
public boolean login(String theUserId, String thePassword) {
return profile.authenticate(theUserId, thePassword);
}
}
Profile.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-17
V3.1
EXempty
package lab4;
public class Profile {
private String userId;
private String password;
/**
* Constructor for Profile
*/
public Profile() {
super();
}
/**
* Create the Profile
* @param theUserId The user id to set
* @param thePassword The password to set.
*/
public Profile(String theUserId, String thePassword) {
super();
setUserId(theUserId);
setPassword(thePassword);
}
/**
* Gets the userId
* @return Returns a String
*/
public String getUserId() {
return userId;
}
/**
* Sets the userId
* @param userId The userId to set
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* Gets the password
* @return Returns a String
*/
public String getPassword() {
return password;
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-18 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
}
/**
* Sets the password
* @param password The password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Authenticate the user ID and password
* @param theUserId The user ID to be authenticated
* @param thePassword The password to be authenticated
* @return Returns true if the user ID and password are valid
*/
public boolean authenticate(String theUserId, String
thePassword) {
if (theUserId == null || thePassword == null) {
return false;
}
return (theUserId.equals(userId) &&
thePassword.equals(password));
}
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-1
V3.1
EXempty
Exercise 5. Class Methods and Variables
What This Exercise Is About
In this exercise you will reuse the Customer and Profile classes that
you created in exercise 12. In addition you will create Cupboard and
Test classes. The Cupboard class is a static repository that contains a
collection of Customer references and a collection of Test instances.
The UML class diagrams shown below depict the classes that you will
create in this exercise.
Customer
-name : String
-eMail : String
-profile : Profile
+Customer(String,String) :
+Customer() :
+createProfile(String,String,String) : void
+getEMail() : String
+getName() : String
+getProfile() : Profile
+login(String, String) : boolean
+setEmail(String) : void
+setName(String) : void
+setProfile(Profile) : void
Driver
+main(String[]) : void
Cupboard
-customerCollection : Vector
-testCollection : Vector
+init() : void
+listTests(Customer) : void
+login(String,String) : Customer
Test
+DEVELOPMENT : String = "DEVELOPMENT"
+PRODUCTON : String = "PRODUCTON"
-nextTestdNumber : int = 1
-name : String
-area : String
-idNumber : int
-status : String
+Test()
+Test(String,String) :
+getArea() : String
+getdNumber() : int
+getName() : String
-getNextTestdNumber() : int
+getStatus() : String
+setArea(String) : void
+setdNumber(String) : void
+setName(String) : void
+setStaus(String) : void
ProfiIe
+DEVELOPER : String = "DEVELOPER"
+USER: String = "USER"
-password : String
-privilege : String
-userd : String
+Profile() :
+Profile(String,String) :
+authenticate(String,String) : boolean
+getPassword() : String
+getPrivilege() : String
+getUserd() : String
+setPassword(String) : void
+setPrivilege( String) : void
+setUserd(String) : void
0..n
0..n
1
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
What You Should Be Able to Do
At the end of the lab, you should be able to:
Use class methods and variables
Declare class (static) variables
Write class (static) methods
Learning Strategy
Individual exercise
Required Materials
WebSphere Studio Application Developer, Version 5.1
Solutions to lab4 (Creating Classes exercise)
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-3
V3.1
EXempty Exercise Instructions
A Test instance represents a test that is either under development or in production. An
instance variable depicts the test status as being DEVELOPMENT or PRODUCTION.
The Cupboard class is a central repository of instances of Customer and Test. You will
use two java.util.Vector instances to hold the references. Cupboard is implemented using
class methods and class variables (fields). Thus there is only one executable rendition of
Cupboard, making it behave much like a singleton instance. The init() method of Cupboard
will prime its repository vectors with instances Customer and Test.
How does a Customer instance log in under this new version of the application? The
Cupboard has a login method that accepts a user ID and password. Its implementation
delegates to the proper Customer login() method if an instance of that Customer exists in
its repository. The Customer.login() calls the authenticate method of its associated Profile
instance. If anything goes wrong, the Customer isn't logged in.
The Cupboard is able to list the Test instances available to the kind of a given logged in
Customer instance. Each Customer is a consumer of tests of a status that is permissible
for the given kind of Customer. How are kinds of Customer specified?
You shall set the privilege field of Profile class to an appropriate privilege level for the
associated Customer. There are two privileges: USER and DEVELOPER. A USER may
only access tests in PRODUCTION status. A DEVELOPER may only access tests in
DEVELOPMENT status.
You will implement a driver method (main method) in class Driver. The main method will
initialize the Cupboard using its init method. Next you will log in a user ID and password to
the Cupboard. The privilege of the profile will be DEVELOPER. Then your driver will ask
the Cupboard to list the test names available to the kind of Customer that is logged into the
system. Tests of DEVELOPMENT status will display. Finally, you will log in a user ID that
has USER status. Tests of PRODUCTION status will display.
Directions
Step A: Create a package
1. Ensure that WebSphere Studio Application Developer is executing.
2. Close any old edit windows.
a. Menu File -> Close All.
3. Create a package named lab5 within project OO Programming with Java.
a. With the OO Programming with Java project selected, click the Create a Java
Package toolbar button (looks like a wrapped box).
b. In the New Java Package wizard specify a Package name of lab5, and click Finish.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Step B: Reuse existing classes
In this step, you will copy your existing classes to your new package so that you can
continue building upon them.
1. Make sure you are in the Package Explorer view of the Java perspective. Copy the
Driver, Profile, and Customer classes from the previous exercise package, lab4, to
your new empty package lab5.
Information: While it is possible to copy the files from either the Package Explorer
view or the Navigator view you usually want to copy the Java source files from the
Package Explorer view. When you do a copy from the Package Explorer view the
package import statements in the Java source files will be updated to the new locations.
A copy from the Navigator view does a file level copy only and does not update the file
in any way. You would then have to go in and fix the import statements yourself.
a. Verify that you are in the Java perspective by looking at the title bar. If it says Java
- IBM WebSphere Studio Application Developer you are in the Java perspective.
If not, look at the icons in the shortcut bar and click on the first open Java
perspective. If needed, you can open up a new Java perspective by using menu
Window -> Open Perspective -> Java.
b. Make sure you are in the Package Explorer view. Look at the tabs in the lower left
corner from the Java perspective and click the Package Explorer tab.
c. Select the classes in the Package Explorer view from the lab4 package while
holding down the Ctrl key.
d. Right click on the selected classes and choose Copy.
e. Select the lab5 package, right click and choose Paste.
f. Click on the Driver.java class. Notice that the package statement now indicates
lab5.
Step C: Create a Test class
In this step you will create a Test class. This Test class is used to represent a pool of
questions that can be selected for an exam.
Note: Make sure you make all of your changes to lab5 and not to the older packages. The
safest approach would be to close all of your existing edit windows (menu File -> Close All)
and open them up from package lab5 as you need them.
1. Create the public class Test in package lab5. Make its superclass java.lang.Object.
Select only the stub option Constructors from superclass.
Note: The detailed steps have been omitted. If you need help, please see previous
exercises for the step-by-step instructions.
2. Add the fields to the Test class that are represented on the UML diagram and have
Application Developer generate getters and setters for you.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-5
V3.1
EXempty
.
a. For each of these fields use the Outline view to create the getter and setter methods
for the fields.
3. Create a new constructor for the Test class that takes two parameters, the name of the
test, and the area of the test, and initializes the fields.
a. Our solution looks like:
public Test(String theName, String theArea) {
setName(theName);
setArea(theArea);
}
4. Create a class field (static modifier) named nextTestIdNumber, of type int, initialize it
to 1, make it private, and do not generate getter and setter methods.
a. Our solution follows (changes in bold):
public class Test {
private static int nextTestIdNumber = 1;
...
}
Information: From now on, detailed steps of creating fields will be omitted. In the future
you will be given all pertinent details, and be expected create the field within the class
using Application Developer. For instance, the above field will be described as: "Create
a private static int NextTestIdNumber field for the Test class, do not generate getter and
setter methods. Initialize the field to 1."
5. Create a private class method getNextTestIdNumber() for the Test class. This class
(static) method should return the current value of nextTestIdNumber, and then
increment the value of nextTestIdNumber.
a. Our solution follows:
private static int getNextTestIdNumber() {
return nextTestIdNumber++;
}
Information: From now on, detailed steps of creating methods will be omitted. In the
future you will be given all pertinent details, and be expected create the method
within Application Developer. For instance, the above method will be described as:
"Create a private static int getNextTestIdNumber() method for the Test class."
6. Modify Test's two-argument constructor so that it sets the idNumber field to be the next
test id number.
Access Modifier Type Name
private String area
private String name
private int idNumber
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-6 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
a. Select the Test(String, String) constructor. After the current initialization code, use
the setter method for idNumber to set the value to the result returned from
getNextTestIdNumber() message.
Our solution for the constructor now looks like this:
public Test(String theName, String theArea) {
setName(theName);
setArea(theArea);
setIdNumber(getNextTestIdNumber());
}
Note that the call to method getNextTestIdNumber() is important here since the
getNextTestIdNumber() method also increments the value of the class variable
nextTestIdNumber.
b. Save your changes to the Test class and make sure there are no syntax errors in the
Test class.
7. Modify the Driver's main(String[ ]) method to create several tests and print their
information to the Console window.
a. Select the main(String[ ]) method within the Driver class of package lab5.
b. In the main method, after the lines of code to create Customers and Profiles,
create several tests (call the first one "test1", the second "test2", and so forth).
Remember to type the variable to be Test.
Note: It is common to talk about creating test1 as type Test but what you are really
doing is creating test1 as a reference to an object of type Test. The new operator is
creating the instance of Test and then assigning a reference to the new object to the
reference test1. The variable test1 is NOT the test but is a reference to the actual
Test object.
c. Use System.out.println() to print the test name, area, and test number to the
Console window.
d. Our solution (for two tests) looks like this:
Test test1 = new Test("Basic Java2 Syntax",
"Application Development");
System.out.println("The first test's name is: " +
test1.getName() +
", and its area is: " +
test1.getArea() +
", and its test id number is: " +
test1.getIdNumber());
Test test2 = new Test("Java Servlets",
"Application Development");
System.out.println("The second test's name is: " +
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-7
V3.1
EXempty
test2.getName() +
", and its area is: " +
test2.getArea() +
", and its test id number is: " +
test2.getIdNumber());
8. Save the main(String[ ]) method, and run it.
9. The Console window should open (if not already open) and display the following:
Adam logged in successfully
Charlene did not log in successfully
The first test's name is: Basic Java2 Syntax, and its area is:
Application Development, and its test id number is: 1
The second test's name is: Java Servlets, and its area is:
Application Development, and its test id number is: 2
(Note: That each test has a different idNumber.)
Step D: Create the Cupboard class
In this step you will create a class that will hold instances of Test and Customer. In a real
application you need some way to control access to the available tests, and to the
customers. In our application, the Cupboard class is the one that will do this for us.
1. Create the Cupboard class within the lab5 package. Make its superclass be the default
of java.lang.Object. Make sure that none of the stub options are selected.
2. Create a private static testCollection field of type java.util.Vector for the Cupboard
class, do not generate getter and setter methods. Initialize the field to be new
java.util.Vector().
a. Our solution follows:
private static java.util.Vector testCollection =
new java.util.Vector();
3. Create a private static customerCollection field of type java.util.Vector for the
Cupboard class, do not generate getter and setter methods. Initialize the field to be
new java.util.Vector().
4. Create a public static void init() method in the Cupboard class that will create some
instances of Test and add them to the testCollection, and some instances of
Customer and add them to the customerCollection.
a. Much of the code for this method can be cut and pasted from the Driver
main(String[ ]) method. You will have to add the vector support and remove the
login logic and the System.out.println() statements.
Our solution for this method looks like:
public static void init() {
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-8 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Customer theCustomer =
new Customer("Adam", "adam@hotmail.com");
Profile theProfile = new Profile("ADAM", "ADAM123");
theCustomer.setProfile(theProfile);
Customer anotherCustomer =
new Customer("Charlene", "char@email.com");
Profile anotherProfile = new Profile("CHAR", "CHAR321");
anotherCustomer.setProfile(anotherProfile);
customerCollection.add(theCustomer);
customerCollection.add(anotherCustomer);
Test test1 =
new Test("Basic Java2 Syntax", "Application Development");
Test test2 =
new Test("Java Servlets", "Application Development");
testCollection.add(test1);
testCollection.add(test2);
}
5. Create a public static Customer login(String theUserId, String thePassword)
method in the Cupboard class that will search through the customerCollection and
find the one whose profile's userId matches the provided userId and logs them in. If the
customer logs in successfully, return the customer, otherwise return null.
a. Iterate through the objects stored in the customerCollection using a for loop.
b. Remember to cast the retrieved elements from customerCollection to be of type
Customer.
c. If the customer's profile's userId is equal to the userId passed in then attempt to log
the user in.
d. If the user logs in successfully then return the Customer.
e. If the user does not log in successfully, or the customer is not found in the collection,
then return null.
Here is our solution for this method:
public static Customer login(String theUserId,
String thePassword) {
Customer theCustomer = null;
for (int index = 0; index < customerCollection.size(); index++) {
theCustomer = (Customer) customerCollection.get(index);
if (theCustomer.getProfile().getUserId().equals(theUserId)) {
break;
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-9
V3.1
EXempty
}
if (theCustomer != null) {
boolean loggedIn = theCustomer.login(theUserId, thePassword);
if (loggedIn) {
return theCustomer;
}
}
return null;
}
f. Save your changes to the Cupboard class and make sure there are no syntax errors
in the class.
6. Modify the Driver main(String[ ]) method to invoke the init() method of the Cupboard
class, and then attempt to log the two customers in. If the customers log in successfully,
print a welcome message, if not print an access denied message. Make sure one of the
customers logs in and the other one does not.
a. Remove all the existing code from the main(String[ ]) method. (This was all
initialization code that has been moved to the init() method on Cupboard.)
b. Initialize the Cupboard by sending the init() message to the class.
c. Use the login(String, String) method of Cupboard to attempt to log in two
customers (have one be successful, and one not). Remember the login(String,
String) method of Cupboard will return a reference to an instance of Customer if
the login is successful, otherwise it will return null.
Our solution for the main(String[ ]) method looks like this:
public static void main(String[] args) {
Cupboard.init();
Customer someCustomer = Cupboard.login("ADAM", "ADAM123");
if (someCustomer != null) {
System.out.println("Welcome " + someCustomer.getName() +
"you logged in successfully");
} else {
System.out.println("Sorry, access denied");
}
someCustomer = Cupboard.login("CHAR", "WRONGPASSWORD");
if (someCustomer != null) {
System.out.println("Welcome " + someCustomer.getName() +
" you logged in successfully");
} else {
System.out.println("Sorry, access denied");
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-10 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
}
7. Save your classes and run the Driver class.
8. The Console will open (if not already open). Look at the Console output, it should
contain something similar to the following:
Welcome Adam you logged in successfully
Sorry, access denied
Step E: Create constants to define tests and customers
In this step, you will define several constants (using class variables). You need to be able to
differentiate development and production tests, as well as user and developer customers.
1. Add a field to the Test class called status. It should be private, of type String and have
public getter and setter methods.
2. Add a field to the Profile class called privilege. It should be private, of type String and
have public getter and setter methods.
Information: It would be easy enough just to leave this here and not define the
constants. But, you would end up with hard-coded values all over in your application
trying to determine if a test is in development or in production. You will use final, static
variables to define these constants and then access the variables instead of hard
coding the values. The final modifier is used to denote a constant in Java.
3. Add a field to the Test class called DEVELOPMENT (yes, in all upper case letters). It
should be public, final, static, of type String and be initialized to the value
"DEVELOPMENT" (yes, include the quotation marks). Do not create getter and setter
methods for this field.
4. Add a field to the Test class called PRODUCTION. It should be public, final, static, of
type String and be initialized to the value "PRODUCTION". Do not create getter and
setter methods for this field.
5. Modify the Cupboard's init() method to set the status of the tests that are created. Set
one to be PRODUCTION, and the other to be DEVELOPMENT.
a. Use the setStatus(String) method of Test to set the status of each test that is
created. Use Test.PRODUCTION, and Test.DEVELOPMENT for the parameters.
Here is our solution within the init() method of Cupboard:
Test test1 = new Test("Basic Java2 Syntax",
"Application Development");
test1.setStatus(Test.DEVELOPMENT);
Test test2 = new Test("Java Servlets",
"Application Development");
test2.setStatus(Test.PRODUCTION);
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-11
V3.1
EXempty
6. Add a field to the Profile class called USER. It should be public, final, static, of type
String and be initialized to the value "USER". Do not create getter and setter methods
for this field.
7. Add a field to the Profile class called DEVELOPER. It should be public, final, static, of
type String and be initialized to the value "DEVELOPER". Do not create getter and
setter methods for this field.
Information: You could go and modify the init() method of Cupboard to set the
privilege of a profile to Profile.USER or Profile.DEVELOPER. However, you will solve
this problem a little differently. You will encapsulate the fact that the Customer class
uses an instance of Profile. You will have the customer create the profile, rather than
creating the profile externally to customer and then setting it.
8. Add a method createProfile(String, String, String) to the Customer class that takes a
userId, password, and privilege as a parameter. The method should be public, and
have a return type of void. It should create a new instance of Profile and associate it
with the customer.
a. Use the two-argument constructor already defined in Profile, passing the userId and
password as parameters.
b. Using the setPrivilege(String) method of Profile, passing the privilege as a
parameter.
c. Set the profile for this Customer to the Profile you created above.
Our solution looks like this:
public void createProfile(String theUserId,
String thePassword, String thePrivilege) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(thePrivilege);
setProfile(theProfile);
}
9. Modify the Cupboard's init() method to use the createProfile(String, String, String)
method of Customer, instead of using the setProfile(Profile) method. Have one of the
customers be a USER and one be a DEVELOPER.
a. Here is our whole solution for the init() method on Cupboard:
public static void init() {
Customer theCustomer = new Customer("Adam", "adam@hotmail.com");
theCustomer.createProfile("ADAM", "ADAM123", Profile.USER);
Customer anotherCustomer = new Customer("Charlene",
"char@email.com");
anotherCustomer.createProfile("CHAR", "CHAR321",
Profile.DEVELOPER);
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-12 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
customerCollection.add(theCustomer);
customerCollection.add(anotherCustomer);
Test test1 = new Test("Basic Java2 Syntax",
"Application Development");
test1.setStatus(Test.DEVELOPMENT);
Test test2 = new Test("Java Servlets", "Application Development");
test2.setStatus(Test.PRODUCTION);
testCollection.add(test1);
testCollection.add(test2);
}
10. Open Driver's main(String[ ]) method and change Charlene's login to pass her correct
password "CHAR321".
11. Save all of your changes and run the Driver class.
12. The Console window should display the following:
Welcome Adam you logged in successfully
Welcome Charlene you logged in successfully
Step F: Use the constants to list tests for a customer
In this step you will put the constants defined to good use. You will add the ability to list
tests for a customer. A developer should be able to see tests that are in development, and
users should be able to see only tests that are in production.
1. Create a public static void listTests(Customer) method in the Cupboard class that
will search through the testCollection and find the tests that the customer should be
able to see (based on their profile's privilege value). Print the tests that the customer
can see to the Console.
a. Loop through the elements in the testCollection using a for loop.
b. If the test's status is Test.DEVELOPMENT and the customer's profile's privilege is
Profile.DEVELOPER, or the test's status is Test.PRODUCTION and the customer's
profile's privilege is Profile.USER, then print the test out to the console using
System.out.println().
Our solution looks like this:
public static void listTests(Customer theCustomer) {
String filter = "";
if (theCustomer.getProfile().getPrivilege().
equals(Profile.DEVELOPER)) {
filter = Test.DEVELOPMENT;
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-13
V3.1
EXempty
} else if (theCustomer.getProfile().getPrivilege().
equals(Profile.USER)) {
filter = Test.PRODUCTION;
}
for (int index = 0; index < testCollection.size(); index++) {
Test theTest = (Test) testCollection.get(index);
if (theTest.getStatus().equals(filter)) {
System.out.println("\t" + theTest.getIdNumber() +
" : " + theTest.getName() + " : " + theTest.getArea());
}
}
}
2. Modify Driver's main(String[ ]) method to call Cupboard's listTests(Customer)
method with the non-null return of the login(String, String) after printing out the
welcome. (Remember to do this for after both logins.)
a. Our (partial) solution looks like this:
...
if (someCustomer != null) {
System.out.println("Welcome " + someCustomer.getName() +
" you logged in successfully");
Cupboard.listTests(someCustomer);
} else {
System.out.println("Sorry, access denied");
}
...
3. You may wish to add some more tests to the init() method in Cupboard so that it lists
more than one test for each customer. (Our solution has added several more).
4. Save your changes and run the Driver class. The Console view should display the
following:
Welcome Adam you logged in successfully
2 : Java Servlets : Application Development
3 : Java Applets : Application Development
5 : XML Parsers : XML
6 : Beginning HTML : Web Development
Welcome Charlene you logged in successfully
1 : Basic Java2 Syntax : Application Development
4 : XML Tags : XML
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-14 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Summary
You implemented the Cupboard class composed entirely of static variables and methods.
These are often called class variables or class methods because they are associated with
the class. They do not need an instance to be accessed, but if you did instantiate
Cupboard, you could access them from the reference also.
You used the static int nextIdNumber field in the Test class to control the assignment of
unique ID numbers to tests. This is a common solution used where a class must control a
value given to its instances.
END OF LAB
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-15
V3.1
EXempty
Reference code
Below are the classes for this exercise.
package lab5;
public class Cupboard {
private static java.util.Vector testCollection = new java.util.Vector();
private static java.util.Vector customerCollection =
new java.util.Vector();
public static void init() {
Customer theCustomer = new Customer("Adam","adam@hotmail.com");
theCustomer.createProfile("ADAM", "ADAM123", Profile.USER);
Customer anotherCustomer = new Customer("Charlene","char@email.com");
anotherCustomer.createProfile("CHAR", "CHAR321", Profile.DEVELOPER);
customerCollection.add(theCustomer);
customerCollection.add(anotherCustomer);
Test test1 = new Test("Basic Java2 Syntax",
"Application Development");
test1.setStatus(Test.DEVELOPMENT);
Test test2 = new Test("Java Servlets",
"Application Development");
test2.setStatus(Test.PRODUCTION);
Test test3 = new Test("Java Applets", "Application Development");
test3.setStatus(Test.PRODUCTION);
Test test4 = new Test("XML Tags","XML");
test4.setStatus(Test.DEVELOPMENT);
Test test5 = new Test("XML Parsers","XML");
test5.setStatus(Test.PRODUCTION);
Test test6 = new Test("Beginning HTML","Web Development");
test6.setStatus(Test.PRODUCTION);
testCollection.add(test1);
testCollection.add(test2);
testCollection.add(test3);
testCollection.add(test4);
Cupboard.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-16 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
testCollection.add(test5);
testCollection.add(test6);
}
public static Customer login(String theUserId,String thePassword) {
Customer theCustomer = null;
for (int index=0; index < customerCollection.size(); index++) {
theCustomer = (Customer) customerCollection.get(index);
if (theCustomer.getProfile().getUserId().equals(theUserId)) {
break;
}
}
if (theCustomer != null) {
boolean loggedIn = theCustomer.login(theUserId, thePassword);
if (loggedIn) {
return theCustomer;
}
}
return null;
}
public static void listTests(Customer theCustomer) {
String filter = "";
if (theCustomer.getProfile().getPrivilege().
equals(Profile.DEVELOPER)) {
filter = Test.DEVELOPMENT;
} else if (theCustomer.getProfile().getPrivilege().
equals(Profile.USER)) {
filter = Test.PRODUCTION;
}
for (int index = 0; index < testCollection.size(); index++) {
Test theTest = (Test) testCollection.get(index);
if (theTest.getStatus().equals(filter)) {
System.out.println("\t" + theTest.getIdNumber() +
" : " + theTest.getName() + " : " + theTest.getArea());
}
}
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-17
V3.1
EXempty
}
package lab5;
public class Customer {
private String name;
private String eMail;
private Profile profile;
/**
* Constructor for Customer
*/
public Customer() {
super();
}
/**
* Create a new Customer from the specified parameters
* @param theName The name to set
* @param theEMail The eMail to set
*/
public Customer(String theName, String theEMail) {
super();
setName(theName);
setEMail(theEMail);
}
/**
* Gets the name
* @return Returns a String
*/
public String getName() {
return name;
}
/**
* Sets the name
* @param name The name to set
*/
public void setName(String name) {
this.name = name;
}
Customer.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-18 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
/**
* Gets the eMail
* @return Returns a String
*/
public String getEMail() {
return eMail;
}
/**
* Sets the eMail
* @param mail The eMail to set
*/
public void setEMail(String mail) {
eMail = mail;
}
/**
* Gets the profile
* @return Returns a Profile
*/
public Profile getProfile() {
return profile;
}
/**
* Sets the profile
* @param profile The profile to set
*/
public void setProfile(Profile profile) {
this.profile = profile;
}
/**
* Log in with the specified user ID and password.
* @param theUserId User ID to use for the login request
* @param thePassword Password to use for the login request
* @return boolean True if login was a success.
*/
public boolean login(String theUserId, String thePassword) {
return profile.authenticate(theUserId, thePassword);
}
/**
* Create a profile for the Customer
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-19
V3.1
EXempty
* @param theUserId User ID of the customer
* @param thePasswork Password of the customer
* @param thePrivilege Customer's privilege
*/
public void createProfile(String theUserId, String thePassword,
String thePrivilege) {
Profile profile = new Profile(theUserId,thePassword);
profile.setPrivilege(thePrivilege);
setProfile(profile);
}
}
package lab5;
public class Driver {
public static void main(String[] args) {
Cupboard.init();
Customer someCustomer = Cupboard.login("ADAM", "ADAM123");
if (someCustomer != null) {
System.out.println("Welcome " +someCustomer.getName() +
" you logged in successfully");
Cupboard.listTests(someCustomer);
} else {
System.out.println("Sorry, access denied");
}
someCustomer = Cupboard.login("CHAR","CHAR321");
if (someCustomer != null) {
System.out.println("Welcome " +someCustomer.getName() +
" you logged in successfully");
Cupboard.listTests(someCustomer);
} else {
System.out.println("Sorry, access denied");
}
}
}
Driver.java
Profile.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-20 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
package lab5;
public class Profile {
public final static String USER = "USER";
public final static String DEVELOPER = "DEVELOPER";
private String userId;
private String password;
private String privilege;
/**
* Constructor for Profile
*/
public Profile() {
super();
}
/**
* Create the Profile
* @param theUserId The user id to set
* @param thePassword The password to set.
*/
public Profile(String theUserId, String thePassword) {
super();
setUserId(theUserId);
setPassword(thePassword);
}
/**
* Gets the userId
* @return Returns a String
*/
public String getUserId() {
return userId;
}
/**
* Sets the userId
* @param userId The userId to set
*/
public void setUserId(String userId) {
this.userId = userId;
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-21
V3.1
EXempty
/**
* Gets the password
* @return Returns a String
*/
public String getPassword() {
return password;
}
/**
* Sets the password
* @param password The password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Authenticate the user ID and password
* @param theUserId The user ID to be authenticated
* @param thePassword The password to be authenticated
* @return Returns true if the user ID and password are valid
*/
public boolean authenticate(String theUserId, String thePassword) {
if (theUserId == null || thePassword == null) {
return false;
}
return (theUserId.equals(userId) && thePassword.equals(password));
}
/**
* Gets the privilege
* @return Returns a String
*/
public String getPrivilege() {
return privilege;
}
/**
* Sets the privilege
* @param privilege The privilege to set
*/
public void setPrivilege(String privilege) {
this.privilege = privilege;
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-22 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
}
}
package lab5;
public class Test {
public final static String DEVELOPMENT = "DEVELOPMENT";
public final static String PRODUCTION = "PRODUCTION";
private static int nextTestIdNumber = 1;
private String status;
private String area;
private String name;
private int idNumber;
/**
* Constructor for Test
*/
public Test() {
super();
}
/**
* Constructor for Test.
* @param theName Test name
* @param theArea Test area
*/
public Test(String theName, String theArea) {
setName(theName);
setArea(theArea);
setIdNumber(getNextTestIdNumber());
}
/**
* Gets the area
* @return Returns a String
*/
public String getArea() {
return area;
}
/**
Test.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-23
V3.1
EXempty
* Sets the area
* @param area The area to set
*/
public void setArea(String area) {
this.area = area;
}
/**
* Gets the name
* @return Returns a String
*/
public String getName() {
return name;
}
/**
* Sets the name
* @param name The name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the idNumber
* @return Returns a int
*/
public int getIdNumber() {
return idNumber;
}
/**
* Sets the idNumber
* @param idNumber The idNumber to set
*/
public void setIdNumber(int idNumber) {
this.idNumber = idNumber;
}
/**
* Get the next test id
* @return next test id
*/
private static int getNextTestIdNumber() {
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-24 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
return nextTestIdNumber++;
}
/**
* Gets the status
* @return Returns a String
*/
public String getStatus() {
return status;
}
/**
* Sets the status
* @param status The status to set
*/
public void setStatus(String status) {
this.status = status;
}
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 6. Object Hierarchy 6-1
V3.1
EXempty
Exercise 6. Object Hierarchy
What This Exercise Is About
This exercise is about using and adding to the hierarchy of classes.
The UML class diagrams below depict the class structure of the
application.
3HUVRQ {abstract}
-name : String
-eMail : String
-profile : Profile
+Person()
+Person(String,String)
+createProfile(String,String) : void
+getEmail() : String
+getName() : String
+getProfile() : Profile
+login(String, String) : boolean
+setEmail(String) : void
+setName(String) : void
+setProfile(Profile) : void
ProfiIe
+DEVELOPER : String = "DEVELOPER"
+USER : String = "USER"
-password : String
-privilege : String
-userd : String
+Profile()
+Profile(String,String)
+authenticate(String,String) : boolean
+getPassword() : String
+getPrivilege() : String
+getUserd() : String
+setPassword(String) : void
+setPrivilege(String) : void
+setUserd(String) : void
Driver
+main(String[]) : void
Cupboard
-personCollection : Vector
-testCollection : Vector
+init() : void
+listTests(Person) : void
+login(String,String) : Person
Test
+DEVELOPMENT : String = "DEVELOPMENT"
+PRODUCTON : String = "PRODUCTON"
-nextdNumber : int = 1
-name : String
-area : String
-idNumber : int
-status : String
+Test()
+Test(String,String)
+getArea() : String
+getdNumber() : int
+getName : String
-getNextTestdNumber() : int
+getStatus() : String
+setArea(String) : void
+setdNumber(int) : void
+setName(String) : void
+setStatus(String) : void
Customer
+Customer(String,String)
+Customer()
+createProfile(String,String) : void
DeveIoper
+Developer(String,String)
+Developer()
+createProfile(String,String) : void
1
0..n
0..n
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
6-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
What You Should Be Able to Do
At the end of the lab, you should be able to:
Create subclasses
Override methods
Use super()
Required Materials
WebSphere Studio Application Developer, Version 5.1
Solutions in package lab5 (Class Methods and Variables exercise)
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 6. Object Hierarchy 6-3
V3.1
EXempty Exercise Instructions
You will decompose the Customer class of the prior exercise into a small class hierarchy.
The Customer class will become an abstract base class called Person. It will declare an
abstract createProfile(userId, password) method. You will create a Customer subclass and
a Developer subclass of Person. Each will implement the createProfile() method by
creating a profile unique to the kind of subclass. Each kind of Person knows its assigned
exam system privilege level. It will set that privilege into its profile in its override of the
createProfile() method.
Directions
Step A: Create a new package
1. Ensure that Application Developer is executing.
2. Close any old edit windows.
3. Create a package named lab6 within project OO Programming with Java.
Step B: Reuse existing classes
In this step, you will copy your existing classes to your new package so that you can
continue building upon them.
1. Copy the Cupboard, Customer, Driver, Profile, and Test classes from the previous
exercise package to your empty package lab6.
a. Select the classes in the package of the previous exercise while holding down the
Ctrl key.
b. Right-click the selection and then choose Copy from the pop-up menu.
c. Expand project OO Programming with Java and select package lab6. Right-click
the package and select paste.
Step C: Create an abstract base class
In this step you will create an abstract class called Person. Most of the required behavior
for the Person class already exists in the Customer class. Rather than creating the Person
class and copying everything, you will just rename the Customer class to Person. In a
following step you will recreate the Customer class.
1. Rename class Customer to the name Person.
a. Select Customer in package lab6 in the Package view.
b. Right-click and choose Refactor->Rename... from pop-up menu.
c. Notice the options on the Refactoring - Rename Compilation Unit wizard. The
only checkbox necessary is the Update references to the renamed element. Enter
the name Person and then click OK.
Information: When you complete the previous step many things happen. First the
class is renamed, the constructors are renamed (remember a constructor must
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
6-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
have the same name as the class), and all references to Customer were changed
to Person.
2. Edit the Person class, adding the keyword abstract before the class keyword, and
save your changes. You have now introduced errors into class Cupboard.java. Why?
The Person class is abstract and cannot be created by the code in the Cupboard class.
You will fix these errors in later steps.
3. Edit the createProfile(String, String) method of Person. Remove the third parameter,
add the keyword abstract before the return type, and substitute a semicolon (end of
statement) for the body (curly braces, and everything within them). Save the method.
You have introduced two new errors into the Cupboard class.
a. The method should look like this:
public abstract void createProfile(String theUserId,
String thePassword);
Step D: Extend the Person class with Customer and Developer classes
1. Create a Customer class that extends Person.
a. Select the package lab6 within the OO Programming with Java project.
b. Click the Create a Java Class toolbar button.
c. Type Customer in the Name: field, and type Person in the Superclass: field.
d. Select the options Constructors from superclass and Inherited abstract
methods from the stub options.
e. Click Finish.
Information: Examine the Customer class. You will see three methods that
Application Developer generated for you: a zero-argument constructor, a
two-argument constructor, and a createProfile(String, String) method. Examine
the code in the two-argument constructor. The code is: super(theName, theEMail).
This constructor uses the superclass' two-argument constructor. Also examine the
createProfile(String, String) method. It does not have any code defined for it, just a
set of curly braces. This method was created because the superclass, Person,
defined an abstract method that concrete subclasses must implement.
2. Code the implementation for Customer's createProfile(String, String) by creating a
new instance of Profile using the theUserId and thePassword parameters. Be sure to
use the static constant Profile.USER for the privilege. Then set the profile for the
customer to be this new instance of Profile. This distinguishes a Customer from other
kinds of Person.
a. Our solution looks like:
public void createProfile(String theUserId, String thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.USER);
setProfile(theProfile);
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 6. Object Hierarchy 6-5
V3.1
EXempty
}
3. Create a Developer class that extends Person (use the same steps as you used to
create the Customer class above.
4. Code the implementation for Developer's createProfile(String, String). Use the same
format as used for Customer's, but use the static constant Profile.DEVELOPER for
the privilege value.
Step E: Modify class Cupboard
In this step you will modify the Cupboard class so that it can use (and store) Persons
rather than just Customers. You will then modify the init() method to load Person
references that have DEVELOPER or USER privilege according to whether the person is
an instance of Customer or Developer.
1. Rename Cupboard.customerCollection to personCollection to indicate that the
collection is generic.
a. Select field customerCollection in the expansion of class Cupboard in lab6.
b. Right-click and select Refactor->Rename... , replace the name
customerCollection with personCollection and click OK.
2. Modify the Cupboard.init() method. Your init method has two Person variables.
Change theCustomer and anotherCustomer to thePerson and anotherPerson to
alleviate any confusion as to the type of objects they are referencing. Create one
person as a type Customer and one as a type Developer.
a. Notice that the type of theCustomer is really Person, this was changed when you
renamed Customer to Person at the start of this lab.
b. Change the new to create a new Customer object and assign that new instance to
theCustomer variable. Change theCustomer to thePerson.
c. In the call of createProfile(), remove the third parameter.
Information: Now that you have created Customer as a subclass of Person, and
defined the createProfile(String, String) in Customer to use Profile.USER, you no
longer need to pass it from this creation statement.
d. In the creation of the anotherCustomer change the class that you are creating an
instance of to Developer. Change anotherCustomer to anotherPerson.
e. In the call to createProfile(), remove the third parameter (Note: Since this is an
instance of Developer the createProfile(String, String) method in the Developer
class uses Profile.DEVELOPER.)
f. Change the variable names in the personCollection statements where
theCustomer and anotherCustomer are added to be thePerson and
anotherPerson.
Here's our solution for the first several lines of the init() method:
...
Person thePerson = new Customer("Adam", "adam@hotmail.com");
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
6-6 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
thePerson.createProfile("ADAM", "ADAM123");
Person anotherPerson = new Developer("Charlene", "char@email.com");
anotherPerson.createProfile("CHAR", "CHAR321");
personCollection.add(thePerson);
personCollection.add(anotherPerson);
...
g. Save the Cupboard class. Notice that there are no longer any errors in the init
method.
3. Notice that the Cupboard's login(String, String) method now has a return type of
Person. Change all references to theCustomer to thePerson. Return a matching
Person reference from the personCollection.
a. Here is our solution for this method:
public static Person login(String theUserId, String thePassword) {
Person thePerson = null;
for (int index = 0; index < personCollection.size(); index++) {
thePerson = (Person) personCollection.get(index);
if (thePerson.getProfile().getUserId().equals(theUserId)) {
break;
}
}
if (thePerson != null) {
boolean loggedIn = thePerson.login(theUserId, thePassword);
if (loggedIn) {
return thePerson;
}
}
return null;
}
4. Update the Cupboard classs listTests method. Change all occurrences of
theCustomer to thePerson.
a. You can either change the text by hand or you can use menu Edit-> Find/Replace
to change the text.
5. Save your changes to the Cupboard class and make sure there are no syntax errors in
the class.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 6. Object Hierarchy 6-7
V3.1
EXempty
Step F: Test the program
1. Save all of your changes. There should no longer be any errors.
2. Run the main(String[ ]) method of the Driver class.
3. The Console window should display the following:
Welcome Adam you logged in successfully
2 : Java Servlets : Application Development
3 : Java Applets : Application Development
5 : XML Parsers : XML
6 : Beginning HTML : Web Development
Welcome Charlene you logged in successfully
1 : Basic Java2 Syntax : Application Development
4 : XML Tags : XML
Summary
This program exhibits the behavior of the version of the application that you completed in
the prior exercise. In that exercise you had a collection of Customer references, each
having one of two profile privileges.
In this exercise you created a collection of Person references. Each reference has a
concrete type of either Customer or Developer. The constructors of Customer and
Developer each use super(...) to pass arguments to the Person constructor. Application
Developer inserted this code for you automatically.
Each Person reference has a profile privilege unique to its concrete type. Each of the
subclasses of Person will override the createProfile() method and set its privilege by calling
the setProfile() method implemented in the base class Person. Application Developer
created the empty createProfile() override method for you because createProfile() is an
abstract method and you selected the inherited abstract methods option on the Create
Class wizard.
The driver passes this Person to Cupboard.listTests(Person). Here, the test collection is
filtered and displayed according to the Person's profile privilege, as in the prior exercise.
END OF LAB
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
6-8 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Reference Code
package lab6;
public class Cupboard {
private static java.util.Vector testCollection = new java.util.Vector();
private static java.util.Vector personCollection =
new java.util.Vector();
public static void init() {
Person thePerson = new Customer("Adam","adam@hotmail.com");
thePerson.createProfile("ADAM", "ADAM123");
Person anotherPerson = new Developer("Charlene","char@email.com");
anotherPerson.createProfile("CHAR", "CHAR321");
personCollection.add(thePerson);
personCollection.add(anotherPerson);
Test test1 = new Test("Basic Java2 Syntax",
"Application Development");
test1.setStatus(Test.DEVELOPMENT);
Test test2 = new Test("Java Servlets", "Application Development");
test2.setStatus(Test.PRODUCTION);
Test test3 = new Test("Java Applets", "Application Development");
test3.setStatus(Test.PRODUCTION);
Test test4 = new Test("XML Tags","XML");
test4.setStatus(Test.DEVELOPMENT);
Test test5 = new Test("XML Parsers","XML");
test5.setStatus(Test.PRODUCTION);
Test test6 = new Test("Beginning HTML","Web Development");
test6.setStatus(Test.PRODUCTION);
testCollection.add(test1);
testCollection.add(test2);
testCollection.add(test3);
Cupboard.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 6. Object Hierarchy 6-9
V3.1
EXempty
testCollection.add(test4);
testCollection.add(test5);
testCollection.add(test6);
}
public static Person login(String theUserId,String thePassword) {
Person thePerson = null;
for (int index=0; index < personCollection.size(); index++) {
thePerson = (Person) personCollection.get(index);
if (thePerson.getProfile().getUserId().equals(theUserId)) {
break;
}
}
if (thePerson != null) {
boolean loggedIn = thePerson.login(theUserId, thePassword);
if (loggedIn) {
return thePerson;
}
}
return null;
}
public static void listTests(Person thePerson) {
String filter = "";
if (thePerson.getProfile().getPrivilege().
equals(Profile.DEVELOPER)) {
filter = Test.DEVELOPMENT;
} else if (thePerson.getProfile().getPrivilege().
equals(Profile.USER)) {
filter = Test.PRODUCTION;
}
for (int index = 0; index < testCollection.size(); index++) {
Test theTest = (Test) testCollection.get(index);
if (theTest.getStatus().equals(filter)) {
System.out.println("\t" + theTest.getIdNumber() +
" : " + theTest.getName() + " : " + theTest.getArea());
}
}
}
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
6-10 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
package lab6;
public class Customer extends Person {
/**
* Constructor for Customer
*/
public Customer() {
super();
}
/**
* Constructor for Customer
*/
public Customer(String theName, String theEMail) {
super(theName, theEMail);
}
/**
* @see Person#createProfile(String, String)
*/
public void createProfile(String theUserId, String thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.USER);
setProfile(theProfile);
}
}
package lab6;
public class Developer extends Person {
/**
* Constructor for Developer
*/
public Developer() {
super();
}
Customer.java
Developer.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 6. Object Hierarchy 6-11
V3.1
EXempty
/**
* Constructor for Developer
*/
public Developer(String theName, String theEMail) {
super(theName, theEMail);
}
/**
* @see Person#createProfile(String, String)
*/
public void createProfile(String theUserId, String thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.DEVELOPER);
setProfile(theProfile);
}
}
package lab6;
public class Driver {
public static void main(String[] args) {
Cupboard.init();
Person someCustomer = Cupboard.login("ADAM", "ADAM123");
if (someCustomer != null) {
System.out.println("Welcome " +someCustomer.getName() +
" you logged in successfully");
Cupboard.listTests(someCustomer);
} else {
System.out.println("Sorry, access denied");
}
someCustomer = Cupboard.login("CHAR","CHAR321");
if (someCustomer != null) {
System.out.println("Welcome " +someCustomer.getName() +
" you logged in successfully");
Cupboard.listTests(someCustomer);
} else {
System.out.println("Sorry, access denied");
}
}
}
Driver.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
6-12 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
package lab6;
public abstract class Person {
private String name;
private String eMail;
private Profile profile;
/**
* Constructor for Customer
*/
public Person() {
super();
}
/**
* Create a new Customer from the specified parameters
* @param theName The name to set
* @param theEMail The eMail to set
*/
public Person(String theName, String theEMail) {
super();
setName(theName);
setEMail(theEMail);
}
/**
* Gets the name
* @return Returns a String
*/
public String getName() {
return name;
}
/**
* Sets the name
* @param name The name to set
*/
public void setName(String name) {
this.name = name;
}
Person.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 6. Object Hierarchy 6-13
V3.1
EXempty
/**
* Gets the eMail
* @return Returns a String
*/
public String getEMail() {
return eMail;
}
/**
* Sets the eMail
* @param mail The eMail to set
*/
public void setEMail(String mail) {
eMail = mail;
}
/**
* Gets the profile
* @return Returns a Profile
*/
public Profile getProfile() {
return profile;
}
/**
* Sets the profile
* @param profile The profile to set
*/
public void setProfile(Profile profile) {
this.profile = profile;
}
/**
* Log in with the specified user ID and password.
* @param theUserId User ID to use for the login request
* @param thePassword Password to use for the login request
* @return boolean True if login was a success.
*/
public boolean login(String theUserId, String thePassword) {
return profile.authenticate(theUserId, thePassword);
}
/**
* Create a profile for the Customer
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
6-14 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
* @param theUserId User ID of the customer
* @param thePasswork Password of the customer
*/
public abstract void createProfile(String theUserId, String thePassword);
}
package lab6;
public class Profile {
public final static String USER = "USER";
public final static String DEVELOPER = "DEVELOPER";
private String userId;
private String password;
private String privilege;
/**
* Constructor for Profile
*/
public Profile() {
super();
}
/**
* Create the Profile
* @param theUserId The user id to set
* @param thePassword The password to set.
*/
public Profile(String theUserId, String thePassword) {
super();
setUserId(theUserId);
setPassword(thePassword);
}
/**
* Gets the userId
* @return Returns a String
*/
public String getUserId() {
return userId;
}
Profile.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 6. Object Hierarchy 6-15
V3.1
EXempty
/**
* Sets the userId
* @param userId The userId to set
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* Gets the password
* @return Returns a String
*/
public String getPassword() {
return password;
}
/**
* Sets the password
* @param password The password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Authenticate the user ID and password
* @param theUserId The user ID to be authenticated
* @param thePassword The password to be authenticated
* @return Returns true if the user ID and password are valid
*/
public boolean authenticate(String theUserId, String thePassword) {
if (theUserId == null || thePassword == null) {
return false;
}
return (theUserId.equals(userId) &&
thePassword.equals(password));
}
/**
* Gets the privilege
* @return Returns a String
*/
public String getPrivilege() {
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
6-16 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
return privilege;
}
/**
* Sets the privilege
* @param privilege The privilege to set
*/
public void setPrivilege(String privilege) {
this.privilege = privilege;
}
}
package lab6;
public class Test {
public final static String DEVELOPMENT = "DEVELOPMENT";
public final static String PRODUCTION = "PRODUCTION";
private static int nextTestIdNumber = 1;
private String status;
private String area;
private String name;
private int idNumber;
/**
* Constructor for Test
*/
public Test() {
super();
}
/**
* Constructor for Test.
* @param theName Test name
* @param theArea Test area
*/
public Test(String theName, String theArea) {
setName(theName);
setArea(theArea);
setIdNumber(getNextTestIdNumber());
}
Test.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 6. Object Hierarchy 6-17
V3.1
EXempty
/**
* Gets the area
* @return Returns a String
*/
public String getArea() {
return area;
}
/**
* Sets the area
* @param area The area to set
*/
public void setArea(String area) {
this.area = area;
}
/**
* Gets the name
* @return Returns a String
*/
public String getName() {
return name;
}
/**
* Sets the name
* @param name The name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the idNumber
* @return Returns a int
*/
public int getIdNumber() {
return idNumber;
}
/**
* Sets the idNumber
* @param idNumber The idNumber to set
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
6-18 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
*/
public void setIdNumber(int idNumber) {
this.idNumber = idNumber;
}
/**
* Get the next test id
* @return next test id
*/
private static int getNextTestIdNumber() {
return nextTestIdNumber++;
}
/**
* Gets the status
* @return Returns a String
*/
public String getStatus() {
return status;
}
/**
* Sets the status
* @param status The status to set
*/
public void setStatus(String status) {
this.status = status;
}
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-1
V3.1
EXempty
Exercise 7. Packages
What This Exercise Is About
In this exercise you will reuse the classes you created in the prior
exercise, but you will place those classes into packages and use
access modifiers to control visibility. You will also create a new kind of
Person: a Reviewer class that will reside in its own package. The UML
class diagrams shown below depict the classes you will use in the
exercise.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
3HUVRQ
-name : String
-eMail : String
-profile : Profile
+Person()
+Person(String,String)
+createProfile(String,String) : void
+getEmail() : String
+getName() : String
+getProfile() : String
+login(String, String) : boolean
+setEmail(String) : void
+setName(String) : void
+setProfile(Profile) : void
ProfiIe
+DEVELOPER : String = "DEVELOPER"
+REVEWER : String = "REVEWER"
+USER : String = "USER"
-password : String
-privilege : String
-userd : String
+Profile(String,String)
+Profile()
~authenticate(String,String) : boolean
+getPassword() : String
+getPrivilege() : String
+getUserd() : String
+setPassword(String) : void
+setPrivilege(String) : void
+setUserd(String) : void
Driver
+main(String[]) : void
Cupboard
-personCollection : Vector
-testCollection : Vector
+init() : void
+listTests(Person) : void
+login(String,String) : Person
Test
+DEVELOPMENT : String = "DEVELOPMENT"
+PRODUCTON : String = "PRODUCTON"
-nextdNumber : int = 1
-name : String
-area : String
-idNumber : int
-status : String
+Test()
+Test(String,String)
+getArea() : String
+getdNumber() : int
+getName : String
-getNextTestdNumber() : int
+getStatus() : String
+setArea(String) : void
+setdNumber(int) : void
+setName(String) : void
+setStatus(String) : void
Customer
+Customer(String,String)
+Customer()
+createProfile(String,String) : void
DeveIoper
+Developer(String,String)
+Developer()
+createProfile(String,String) : void
Reviewer
+Reviewer()
+Reviewer(String,String)
+createProfile(String,String) : void
1
0..n
0..n
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-3
V3.1
EXempty What You Should Be Able to Do
At the end of the lab, you should be able to:
Create subclasses
Use the instanceof keyword
Override methods
Use super() and super
Required Materials
WebSphere Studio Application Developer, Version 5.1
Solutions to package lab6 (Object Hierarchy exercise)
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Exercise Instructions
Prior to this exercise you've been placing your classes in a single package without really
thinking about what packages are. Packages help you avoid name collisions, promote
encapsulation through access modifiers, and are a delivery vehicle for functionally related
classes.
In this exercise you will place your Driver class into a separate package named
lab7.driver. You will continue to use the application model packages you created in the
prior exercise, but will move them into a lab7.model package. You will create a new class
called Reviewer that extends Person. It will reside in the lab7.model.reviewer package.
You will apply appropriate access modifiers to enable only the visibility required between
classes, to promote encapsulation.
Directions
In some places you will be asked to temporarily cause a compile error, there errors will
show up in the Tasks view.
Step A: Create packages
1. Ensure that WebSphere Studio Application Developer is running.
2. Close any old edit windows.
3. Create a package named lab7.model in project OO Programming with Java.
4. Create a package named lab7.model.reviewer in project OO Programming with
Java.
Information: When you created the lab7.model.reviewer package the lab7.model
package was hidden from you. The reason for this is that the package view filters empty
non-leaf packages. Once we put a class into the package you will be able to see it.
5. Create a package named lab7.driver in project OO Programming with Java.
Step B: Reuse existing classes
1. Copy the Cupboard, Customer, Developer, Person, Profile, and Test classes from
the previous exercise package to your empty package lab7.model. You can turn the
filter off to see the empty lab7.model package by selecting the Menu button ( small
black triangle in the upper right hand corner of the Package Explorer) and then
Filters... Deselect Empty parent packages and click OK. These classes form the
application model (Refer to previous exercises if you need step-by-step directions for
this procedure.)
2. Copy the Driver class to your new lab7.driver package.
3. The main(String[ ]) method has some errors. It is trying to reference Cupboard and
Person, but they are defined in package lab7.model. Fix these errors by importing the
package lab7.model into the Driver class.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-5
V3.1
EXempty
a. Edit the Driver class and add the following line after the package statement:
import lab7.model.*;
Information: You could have had Application Developer create class import
statements for you. To do this you could have right-clicked and used Organize
Imports from within the pop-up menu. This would have found that classes
Cupboard and Person are in multiple packages and you would have been prompted
for the ones you wanted to import. Application Developer would have added class
level import statements for you. If you had used Source -> Organize Imports the
class would look as follows:
package lab7.driver;
import lab7.model.Cupboard;
import lab7.model.Person
public class Driver {
...
}
Use menu Window -> Preferences to open up the Preferences dialog. Under Java
-> Organize Imports you can specify options to be used when ordering and adding
import statements to your code (using the Organize Imports pop-up menu from the
editor). By changing the Number of qualified imports... option to 1 you can force
Application Developer to create package level imports instead of class imports.
b. Save your changes and the errors will be resolved.
Step C: Impose access modifiers
1. Remove the public access modifier (that is, give it the default protection level) of
Profile.authenticate(String, String). This means that only members of the lab7.model
package can see this method. If you had tightened the access to private, then class
Person would not be able to call this method from its login method even though Person
is in the same package.
2. Save your changes to the Profile class. There should be no syntax errors.
3. Ensure that the access modifier of Test.getNextTestIdNumber() is private. This
ensures that only members of class Test may call this method. This is desirable since
the ID number sequence is a private implementation detail within class Test.
4. Save your changes (if any) to the Test class. There should be no syntax errors.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-6 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Step D: Enhance the Profile class
1. Create a new public final static String variable named REVIEWER in the Profile
class. Give it a value of "REVIEWER". This constant will be used to distinguish a new
profile privilege.
2. Save your changes to class Profile. There should be no syntax errors.
Step E: Create a class Reviewer in package lab7.model.reviewer
1. Create class Reviewer in package lab7.model.reviewer. Extend class Person in
package lab7.model. The Reviewer class profile will be given the new
Profile.REVIEWER privilege.
a. Select the lab7.model.reviewer package in the OO Programming with Java
project.
b. Click the Create a Java Class toolbar button.
c. Notice that the package is lab7.model.reviewer (this is because you selected that
package before you clicked the Create a Java Class toolbar button).
d. Type Reviewer in the Name: field, and type lab7.model.Person in the Superclass:
field.
e. Make sure the Constructors from superclass and Inherited abstract methods
options are selected.
f. Click the Finish button.
2. Implement the createProfile(String, String) method. Use the Profile.Reviewer
constant to specify the REVIEWER privilege for a new associated profile. Add any
import statements needed for class Profile.
a. Our solution looks like:
public void createProfile(String theUserId, String thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.REVIEWER);
setProfile(theProfile);
}
b. You need an import statement for class Profile. To do this bring up a pop-up menu
and select option Source -> Organize Imports. You will be asked which version of
Profile you are trying to import. Select lab7.model.Profile and click Finish.
c. Notice that your class now contains the statement:
import lab7.model.Profile;
3. Save your changes. There should not be any syntax errors in class Reviewer.
Step F: (Optional) Explore access modifiers
1. The createProfile(String, String) methods defined in Customer, Developer and
Reviewer work because the access modifier of the createProfile(String, String)
method in Person is public. What happens if you temporarily remove the access
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-7
V3.1
EXempty
modifier from method createProfile(String, String) in class Customer? By doing this
you are giving the method the default access. Does this work, or does it cause a
compiler error? It causes a compiler error, because you are attempting to reduce the
visibility of an inherited method and Java does not allow this. If you have done this
change the access modifier back to public. What happens if you change the access
modifier in the Person class? Remove the access modifier from the createProfile()
method in class Person. This works for classes Customer, and Developer because
they have access to the method (they are in the same package) and they can expand
the visibility of a method at the subclass level. Class Reviewer still has a problem
because it does not have access to the createProfile() method and it cannot override
the method.
What happens if you change the access modifier for The Person classs
createProfile() method to protected? Now Customer, Developer and Reviewer can
all override the method and can increase the visibility.
If you have made these changes, change the Person classs createProfile() method so
it has an access modifier of public.
2. Temporarily modify the public access modifier of the Cupboard's login(String, String)
method to protected and save your changes. What happens to class
lab7.driver.Driver? Why?
Hint: See the entries in the Tasks view.
3. Restore the method to public access. and save your changes.
4. Ensure that there are no errors in the project.
Step G: Enhance class Cupboard
1. Modify the init() method to create an instance of Reviewer. Add the reviewer to the
personCollection.
a. Here is a partial solution:
...
Person aReviewer = new Reviewer("Edward", "Ed@ed.org");
aReviewer.createProfile("ED", "ED456");
...
personCollection.add(aReviewer);
...
2. From the edit window bring up the pop-up menu and select menu option Organize
Imports. This will then add the import for class lab7.model.reviewer.Reviewer to your
Cupboard class.
3. Modify the listTests(Person) method of class Cupboard to list all tests if the Profile
has a privilege of REVIEWER.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-8 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
a. Our solution looks like:
public static void listTests(Person thePerson) {
String filter = "";
if (thePerson.getProfile().getPrivilege().
equals(Profile.DEVELOPER)) {
filter = Test.DEVELOPMENT;
} else if (thePerson.getProfile().getPrivilege().
equals(Profile.USER)) {
filter = Test.PRODUCTION;
} else if (thePerson.getProfile().getPrivilege()
.equals(Profile.REVIEWER)) {
filter = "ALL";
}
for (int index = 0; index < testCollection.size(); index++) {
Test theTest = (Test) testCollection.get(index);
if (theTest.getStatus().equals(filter) ||
filter.equals("ALL")) {
System.out.println("\t" + theTest.getIdNumber() +
" : " + theTest.getName() + " : " + theTest.getArea());
}
}
}
4. Save your changes to class Cupboard. There should be no syntax errors.
Step H: Modify the Driver class to login a reviewer
1. In the Driver.main(String[ ] args) method, use Cupboard's login(String, String) to
login the Reviewer that you previously added in the init() method of Cupboard.
Use the same format as you did for the other persons.
a. Our partial solution looks like:
...
someCustomer = Cupboard.login("ED", "ED456");
if (someCustomer != null) {
System.out.println("Welcome " + someCustomer.getName() +
" you logged in successfully");
Cupboard.listTests(someCustomer);
} else {
System.out.println("Sorry, access denied");
}
...
b. As always, save your changes and make sure there are no syntax errors.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-9
V3.1
EXempty
Step I: Run the application
1. Run Driver's main(String[ ]) method.
2. The Console view should display the following:
Welcome Adam you logged in successfully
2 : Java Servlets : Application Development
3 : Java Applets : Application Development
5 : XML Parsers : XML
6 : Beginning HTML : Web Development
Welcome Charlene you logged in successfully
1 : Basic Java2 Syntax : Application Development
4 : XML Tags : XML
Welcome Edward you logged in successfully
1 : Basic Java2 Syntax : Application Development
2 : Java Servlets : Application Development
3 : Java Applets : Application Development
4 : XML Tags : XML
5 : XML Parsers : XML
6 : Beginning HTML : Web Development
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-10 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Summary
You refactored your classes from the previous exercises into two packages. You restricted
access to some members. An optional step had you temporarily change some access
modifiers so that you could see the consequences. Access modifiers are important in
enforcing object concepts like encapsulation.
Packages are a necessity in Java to promote reusability and prevent name collisions. For
instance, as you worked through the exercises you may have noticed that you have
accumulated several classes called Profile. You kept them separated and you controlled
where they were used by making them members of uniquely named packages (lab3, lab4,
and so forth).
You used the import statement to tell the compiler where to search for classes. This allows
you to avoid having to use fully qualified names in the source code. It also avoids
hard-coding fully qualified names in the case where the class may need to be loaded from
another package because of modifications during development. It is easier to change an
import statement than a set of scattered fully qualified names. The import may specify
every class in a package or it may reference just one class. The import statement does not
influence bytecode size or execution speed. The import statement is only used by the
compiler to put the fully qualified name into the byte codes. By the time the JVM loads the
class the fully qualified name is used within the byte code.
Packages are also a unit of deployment and reuse. You could deploy your model classes
independently of our driver class. For instance, you could reuse your model classes in a
transaction based non-GUI version of our application. You could also deploy your model
package along with a presentation package that uses Swing classes to implement a GUI
version of your application.
END OF LAB
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-11
V3.1
EXempty
Reference Code
package lab7.model;
import java.util.Vector;
import lab7.model.reviewer.Reviewer;
public class Cupboard {
private static Vector testCollection = new Vector();
private static Vector personCollection = new Vector();
public static void init() {
Person thePerson = new Customer("Adam","adam@hotmail.com");
thePerson.createProfile("ADAM", "ADAM123");
Person anotherPerson = new Developer("Charlene","char@email.com");
anotherPerson.createProfile("CHAR", "CHAR321");
Person aReviewer = new Reviewer("Edward", "Ed@ed.org");
aReviewer.createProfile("ED","ED456");
personCollection.add(thePerson);
personCollection.add(anotherPerson);
personCollection.add(aReviewer);
Test test1 = new Test("Basic Java2 Syntax",
"Application Development");
test1.setStatus(Test.DEVELOPMENT);
Test test2 = new Test("Java Servlets", "Application Development");
test2.setStatus(Test.PRODUCTION);
Test test3 = new Test("Java Applets", "Application Development");
test3.setStatus(Test.PRODUCTION);
Test test4 = new Test("XML Tags","XML");
test4.setStatus(Test.DEVELOPMENT);
Test test5 = new Test("XML Parsers","XML");
Cupboard.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-12 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
test5.setStatus(Test.PRODUCTION);
Test test6 = new Test("Beginning HTML","Web Development");
test6.setStatus(Test.PRODUCTION);
testCollection.add(test1);
testCollection.add(test2);
testCollection.add(test3);
testCollection.add(test4);
testCollection.add(test5);
testCollection.add(test6);
}
public static Person login(String theUserId,String thePassword) {
Person thePerson = null;
for (int index=0; index < personCollection.size(); index++) {
thePerson = (Person) personCollection.get(index);
if (thePerson.getProfile().getUserId().equals(theUserId)) {
break;
}
}
if (thePerson != null) {
boolean loggedIn = thePerson.login(theUserId, thePassword);
if (loggedIn) {
return thePerson;
}
}
return null;
}
public static void listTests(Person thePerson) {
String filter = "";
if (thePerson.getProfile().getPrivilege().
equals(Profile.DEVELOPER)) {
filter = Test.DEVELOPMENT;
} else if (thePerson.getProfile().getPrivilege().
equals(Profile.USER)) {
filter = Test.PRODUCTION;
} else if (thePerson.getProfile().getPrivilege().
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-13
V3.1
EXempty
equals(Profile.REVIEWER)) {
filter = "ALL";
}
for (int index = 0; index < testCollection.size(); index++) {
Test theTest = (Test) testCollection.get(index);
if (theTest.getStatus().equals(filter) ||
filter.equals("ALL")) {
System.out.println("\t" + theTest.getIdNumber() +
" : " + theTest.getName() + " : " + theTest.getArea());
}
}
}
}
package lab7.model;
public class Customer extends Person {
/**
* Constructor for Customer
*/
public Customer() {
super();
}
/**
* Constructor for Customer
*/
public Customer(String theName, String theEMail) {
super(theName, theEMail);
}
/**
* @see Person#createProfile(String, String)
*/
public void createProfile(String theUserId, String thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.USER);
setProfile(theProfile);
}
}
Customer.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-14 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
package lab7.model;
public class Developer extends Person {
/**
* Constructor for Developer
*/
public Developer() {
super();
}
/**
* Constructor for Developer
*/
public Developer(String theName, String theEMail) {
super(theName, theEMail);
}
/**
* @see Person#createProfile(String, String)
*/
public void createProfile(String theUserId, String thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.DEVELOPER);
setProfile(theProfile);
}
}
package lab7.driver;
import lab7.model.*;
public class Driver {
public static void main(String[] args) {
Cupboard.init();
Person someCustomer = Cupboard.login("ADAM", "ADAM123");
if (someCustomer != null) {
System.out.println("Welcome " +someCustomer.getName() +
Developer.java
Driver.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-15
V3.1
EXempty
" you logged in successfully");
Cupboard.listTests(someCustomer);
} else {
System.out.println("Sorry, access denied");
}
someCustomer = Cupboard.login("CHAR","CHAR321");
if (someCustomer != null) {
System.out.println("Welcome " +someCustomer.getName() +
" you logged in successfully");
Cupboard.listTests(someCustomer);
} else {
System.out.println("Sorry, access denied");
}
someCustomer = Cupboard.login("ED","ED456");
if (someCustomer != null) {
System.out.println("Welcome " +someCustomer.getName() +
" you logged in successfully");
Cupboard.listTests(someCustomer);
} else {
System.out.println("Sorry, access denied");
}
}
}
package lab7.model;
public abstract class Person {
private String name;
private String eMail;
private Profile profile;
/**
* Constructor for Customer
*/
public Person() {
super();
}
Person.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-16 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
/**
* Create a new Customer from the specified parameters
* @param theName The name to set
* @param theEMail The eMail to set
*/
public Person(String theName, String theEMail) {
super();
setName(theName);
setEMail(theEMail);
}
/**
* Gets the name
* @return Returns a String
*/
public String getName() {
return name;
}
/**
* Sets the name
* @param name The name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the eMail
* @return Returns a String
*/
public String getEMail() {
return eMail;
}
/**
* Sets the eMail
* @param mail The eMail to set
*/
public void setEMail(String mail) {
eMail = mail;
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-17
V3.1
EXempty
/**
* Gets the profile
* @return Returns a Profile
*/
public Profile getProfile() {
return profile;
}
/**
* Sets the profile
* @param profile The profile to set
*/
public void setProfile(Profile profile) {
this.profile = profile;
}
/**
* Log in with the specified user ID and password.
* @param theUserId User ID to use for the login request
* @param thePassword Password to use for the login request
* @return boolean True if login was a success.
*/
public boolean login(String theUserId, String thePassword) {
return profile.authenticate(theUserId, thePassword);
}
/**
* Create a profile for the Customer
* @param theUserId User ID of the customer
* @param thePasswork Password of the customer
*/
public abstract void createProfile(String theUserId, String thePassword);
}
package lab7.model;
public class Profile {
public final static String USER = "USER";
public final static String DEVELOPER = "DEVELOPER";
public final static String REVIEWER = "REVIEWER";
private String userId;
private String password;
Profile.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-18 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
private String privilege;
/**
* Constructor for Profile
*/
public Profile() {
super();
}
/**
* Create the Profile
* @param theUserId The user id to set
* @param thePassword The password to set.
*/
public Profile(String theUserId, String thePassword) {
super();
setUserId(theUserId);
setPassword(thePassword);
}
/**
* Gets the userId
* @return Returns a String
*/
public String getUserId() {
return userId;
}
/**
* Sets the userId
* @param userId The userId to set
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* Gets the password
* @return Returns a String
*/
public String getPassword() {
return password;
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-19
V3.1
EXempty
/**
* Sets the password
* @param password The password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Authenticate the user ID and password
* @param theUserId The user ID to be authenticated
* @param thePassword The password to be authenticated
* @return Returns true if the user ID and password are valid
*/
boolean authenticate(String theUserId, String thePassword) {
if (theUserId == null || thePassword == null) {
return false;
}
return (theUserId.equals(userId) &&
thePassword.equals(password));
}
/**
* Gets the privilege
* @return Returns a String
*/
public String getPrivilege() {
return privilege;
}
/**
* Sets the privilege
* @param privilege The privilege to set
*/
public void setPrivilege(String privilege) {
this.privilege = privilege;
}
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-20 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
package lab7.model.reviewer;
import lab7.model.Person;
import lab7.model.Profile;
public class Reviewer extends Person {
/**
* Constructor for Reviewer
*/
public Reviewer() {
super();
}
/**
* Constructor for Reviewer
*/
public Reviewer(String theName, String theEMail) {
super(theName, theEMail);
}
/**
* @see Person#createProfile(String, String)
*/
public void createProfile(String theUserId, String thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.REVIEWER);
setProfile(theProfile);
}
}
package lab7.model;
public class Test {
public final static String DEVELOPMENT = "DEVELOPMENT";
public final static String PRODUCTION = "PRODUCTION";
private static int nextTestIdNumber = 1;
Reviewer.java
Test.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-21
V3.1
EXempty
private String status;
private String area;
private String name;
private int idNumber;
/**
* Constructor for Test
*/
public Test() {
super();
}
/**
* Constructor for Test.
* @param theName Test name
* @param theArea Test area
*/
public Test(String theName, String theArea) {
setName(theName);
setArea(theArea);
setIdNumber(getNextTestIdNumber());
}
/**
* Gets the area
* @return Returns a String
*/
public String getArea() {
return area;
}
/**
* Sets the area
* @param area The area to set
*/
public void setArea(String area) {
this.area = area;
}
/**
* Gets the name
* @return Returns a String
*/
public String getName() {
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-22 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
return name;
}
/**
* Sets the name
* @param name The name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the idNumber
* @return Returns a int
*/
public int getIdNumber() {
return idNumber;
}
/**
* Sets the idNumber
* @param idNumber The idNumber to set
*/
public void setIdNumber(int idNumber) {
this.idNumber = idNumber;
}
/**
* Get the next test id
* @return next test id
*/
private static int getNextTestIdNumber() {
return nextTestIdNumber++;
}
/**
* Gets the status
* @return Returns a String
*/
public String getStatus() {
return status;
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-23
V3.1
EXempty
/**
* Sets the status
* @param status The status to set
*/
public void setStatus(String status) {
this.status = status;
}
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-24 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-1
V3.1
EXempty
Exercise 8. Simple I/O and Exceptions
What This Exercise Is About
In this exercise you will handle an exception using an I/O example.
The UML class diagrams shown below are the same as those in the
previous exercise. You will change only the implementation of one
method.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
3HUVRQ
-name : String
-eMail : String
-profile : Profile
+Person()
+Person(String,String)
+createProfile(String,String) : void
+getEmail() : String
+getName() : String
+getProfile() : String
+login(String, String) : boolean
+setEmail(String) : void
+setName(String) : void
+setProfile(Profile) : void
ProfiIe
+DEVELOPER : String = "DEVELOPER"
+REVEWER : String = "REVEWER"
+USER : String = "USER"
-password : String
-privilege : String
-userd : String
+Profile(String,String)
+Profile()
~authenticate(String,String) : boolean
+getPassword() : String
+getPrivilege() : String
+getUserd() : String
+setPassword(String) : void
+setPrivilege(String) : void
+setUserd(String) : void
Driver
+main(String[]) : void
Cupboard
-personCollection : Vector
-testCollection : Vector
+init() : void
+listTests(Person) : void
+login(String,String) : Person
Test
+DEVELOPMENT : String = "DEVELOPMENT"
+PRODUCTON : String = "PRODUCTON"
-nextdNumber : int = 1
-name : String
-area : String
-idNumber : int
-status : String
+Test()
+Test(String,String)
+getArea() : String
+getdNumber() : int
+getName : String
-getNextTestdNumber() : int
+getStatus() : String
+setArea(String) : void
+setdNumber(int) : void
+setName(String) : void
+setStatus(String) : void
Customer
+Customer(String,String)
+Customer()
+createProfile(String,String) : void
DeveIoper
+Developer(String,String)
+Developer()
+createProfile(String,String) : void
Reviewer
+Reviewer()
+Reviewer(String,String)
+createProfile(String,String) : void
1
0..n
0..n
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-3
V3.1
EXempty What You Should Be Able to Do
At the end of the lab, you should be able to:
Do basic I/O operations needed to read files
Handle an I/O exception in code
Required Materials
WebSphere Studio Application Developer, Version 5.1
Solutions in packages lab7.model, lab7.model.reviewer, and
lab7.driver (Packages exercise)
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Exercise Instructions
The previous exercises had you hard-coding customers, reviewers, and developers and
storing them in a collection of persons. You also hardcoded tests and stored them in a
collection of tests. Now you will initialize those collections from a file. You will modify only
the init() method of class Cupboard.
When a program carries out an I/O operation it must include an exception handler, to
handle the situation when an error occurs. The checked code is wrapped in a Java try
block. The exception handler or handlers are specified and implemented by one or more
catch blocks. Each catch block specifies an input parameter of the desired exception type
-- java.io.IOException in this exercise. The parameter is a reference to an instance of an
exception.
You will use a BufferedReader that wraps a FileReader and allows your program to read
the input file with a readLine() method.
Directions
Step A: Create packages
1. Ensure that WebSphere Studio Application Developer is running.
2. Close any old edit windows.
3. Create a package named lab8.model in project OO Programming with Java.
4. Create a package named lab8.model.reviewer in project OO Programming with
Java.
5. Create a package named lab8.driver in project OO Programming with Java.
Step B: Reuse existing classes
1. Copy the Cupboard, Customer, Developer, Person, Profile, and Test classes from
lab7.model to your new lab8.model package.
2. Copy the Driver class from lab7.driver to your new lab8.driver package.
3. Copy the Reviewer class from lab7.model.reviewer to your new lab8.model.reviewer
package.
4. There are four syntax errors that you must fix in order to complete the copy operation.
You must replace the references to lab7.model, and lab7.model.reviewer with
lab8.model, and lab8.model.reviewer.
a. Change the Cupboard class to import lab8.model.reviewer.*
b. Change Driver class to import lab8.model.*.
c. Change Reviewer class to import lab8.model.Profile.
d. Change Reviewer class to import lab8.model.Person.
5. Run your Driver.main(String[ ]) method to make sure that everything has been copied
correctly.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-5
V3.1
EXempty
Step C: Create an initialization file for use by Cupboard.init()
In this step you will replace the hard-coding you used to initialize the Cupboard with data in
external files.
1. Find or create the persons.txt file in the solution directory for lab8. The file is populated
with successive text lines that contain, in turn: name, email, user id, password,
privilege. If you would like to build the file yourself (to use your own data) try to ensure
that you have at least one person representing each of these privileges: DEVELOPER,
USER, or REVIEWER. Here are contents of our persons.txt file:
Adam
adam@hotmail.com
ADAM
ADAM123
USER
Charlene
char@email.com
CHAR
CHAR321
DEVELOPER
Edward
Ed@ed.org
ED
ED456
REVIEWER
a. The persons.txt file is in directory C:\OOPwJava\lab8\solution\
2. Find or create the tests.txt file from the solution directory for lab8. The format for the
tests.txt file is successive text lines that contain, in turn: name, area, and status. The
latter value is either PRODUCTION or DEVELOPMENT. Here are the contents of the
tests.txt file:
Basic Java2 Syntax
Application Development
DEVELOPMENT
Java Servlets
Application Development
PRODUCTION
Java Applets
Application Development
PRODUCTION
XML Tags
XML
DEVELOPMENT
XML Parsers
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-6 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
XML
PRODUCTION
Beginning HTML
Web Development
PRODUCTION
Step D: Modify the Cupboard.init() method to use file I/O
1. Import package java.io into the Cupboard class (or you can wait until later and have
Application Developer create the import for you by using the Organize Imports option
from the editor).
a. Add the statement import java.io.*; either before or after the import statement
for lab8.model.reviewer.*;
2. Comment out the code that currently exists inside the init() method of the Cupboard
class.
Hint: You can comment out the code by putting the code inside a giant /* ... */ comment
block, or you can append a // to every line you want to comment out. You can also let
Application Developer comment out the code for you. The additional steps below will
show you how to do it with Application Developer.
a. Select all of the code in the init method (including any leading tabs and blanks).
b. Bring up a pop-up menu and select Source -> Comment.
c. Verify that all of the code in the init method has been commented out.
3. Create a try block followed directly by a catch block and a finally clause. The catch
block should catch IOException. Within the catch block, print a stack trace and exit the
JVM.
a. Our try block looks like:
try {
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(1);
} finally {
}
4. Just before the try block you need to create a reference to a BufferedReader and
initialize it to null (in our solution we call this field personReader). Within the try block,
create a BufferedReader that wraps a FileReader. The FileReader is instantiated with
the fully qualified persons.txt file as its input parameter. Save the reference to the
BufferedReader in the local field you created above. In a later step you will also be
reading the tests.txt file from the same directory where persons.txt resides. To take
care of this you need to create a new String, prefix, that is initialized to the lab8 solution
directory where the persons.txt and tests.txt files reside. When you reference the
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-7
V3.1
EXempty
persons.txt or tests.txt files you need to concatenate the prefix String with the file
name.
a. Our solution:
String prefix = C:\\OOPwJava\\lab8\\solution\\;
BufferedReader personReader = null;
try {
personReader = new BufferedReader(
new FileReader(prefix+"persons.txt"));
...
Information: This solution is not the ideal one. Hard coding file names and
directories in your application can lead to both deployment and maintenance issues.
Also the file syntax we have used ties our application to a Windows environment. An
alternative would be to use properties files or the class loader getResources support
to add flexibility to the application. Since we are only focused on the I/O classes right
now we have taken a more direct, but less than ideal, approach.
We will be reading two files (persons.txt and tests.txt) from the
C:\OOPwJava\lab8\solution directory. We created the prefix string so we dont have
to hard code the directory structure twice in the code.
Also notice that we had to code C:\OOPwJava\lab8\solution\ as the String
C:\\OOPwJava\\lab8\\solution\\. Why? Recall that the backslash ( \ ) character
indicates that you are coding an escape sequence. To actually include the backslash
itself you have to code the escape sequence \\.
5. After creating the BufferedReader, but still within the try block, code a while loop. Have
it loop as long as the readLine() method for name returns a non-null value. Within the
while loop, read the remaining lines for that person into eMail, userId, password, and
privilege String variables. The code for the following steps should be placed within the
while loop until directed otherwise.
a. Our solution:
...
String name = null;
while ((name = personReader.readLine()) != null) {
String eMail = personReader.readLine();
String userId = personReader.readLine();
String password = personReader.readLine();
String privilege = personReader.readLine();
6. Within your while loop create a new Customer, Developer, or Reviewer based upon
the value read into the privilege variable. Pass the values of name and email. Assign
the new instance to a Person variable named thePerson.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-8 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
a. Our Solution:
Person thePerson = null;
if (privilege.equals("USER")) {
thePerson = new Customer(name, eMail);
} else if (privilege.equals("DEVELOPER")) {
thePerson = new Developer(name, eMail);
} else if (privilege.equals("REVIEWER")) {
thePerson = new Reviewer(name, eMail);
}
7. Create a new profile for the Person by calling its createProfile method. Pass userId
and password.
a. Our solution:
thePerson.createProfile(userId, password);
8. Add the new person to the Cupboard's person collection.
a. Our solution:
personCollection.add(thePerson);
9. Close the while block with a curly right brace.
10. In the finally clause of your try block close the BufferedReader using its close()
method. You need to make sure the input reader is not null and you need to enclose the
close in a try bock.
a. Our solution:
} finally {
try {
if (personReader != null) {
personReader.close();
}
} catch (IOException ioe2) {
}
}
11. Use a similar approach to read in test.txt in init(). Recall that test.txt contains name,
area, and status values for each of the tests to be created.
12. Save your changes and fix any syntax errors. Note that if you didnt code the import for
package java.io earlier you need to do an Organize Imports before you save your
changes.
a. Here is our complete solution to the init() method of Cupboard:
public static void init() {
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-9
V3.1
EXempty
String prefix = C:\\OOPwJava\\lab8\\solution\\;
BufferedReader personReader = null;
try {
personReader = new BufferedReader(
new FileReader(prefix+"persons.txt"));
String name = null;
while ((name = personReader.readLine()) != null){
String eMail = personReader.readLine();
String userId = personReader.readLine();
String password = personReader.readLine();
String privilege = personReader.readLine();
Person thePerson = null;
if (privilege.equals("USER")) {
thePerson = new Customer(name, eMail);
} else if (privilege.equals("DEVELOPER")) {
thePerson = new Developer(name, eMail);
} else if (privilege.equals("REVIEWER")) {
thePerson = new Reviewer(name, eMail);
}
thePerson.createProfile(userId, password);
personCollection.add(thePerson);
}
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(1);
} finally{
try {
if (personReader != null) {
personReader.close();
}
} catch (IOException ioe2) {
}
}
BufferedReader testReader = null;
try {
testReader = new BufferedReader(
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-10 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
new FileReader(prefix+"tests.txt"));
String name = null;
while ((name = testReader.readLine()) != null) {
String area = testReader.readLine();
String status = testReader.readLine();
Test theTest = new Test(name, area);
theTest.setStatus(status);
testCollection.add(theTest);
}
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(1);
} finally{
try {
if (testReader != null) {
testReader.close();
}
} catch (IOException ioe2) {
}
}
}
Step E: Test the code
1. Check for errors. Fix them before running.
2. Execute the main(String[ ]) method on the Driver class. Output should be the same as
the previous exercise, provided that the input data and the main implementation are the
same.
Summary
You added I/O to the application and had to write code to handle a java.io.IOException, a
checked exception. This means that the compiler enforces the handling of the exception.
You must either enclose the code in a try / catch block or specify that the method throws
that exception to any caller. Such a caller would either handle the exception in a try / catch
block or throw the exception in turn.
A non-checked exception has no mandatory handling specified. Handling or throwing is up
to the programmer. An example of a common non-checked exception is a
java.lang.ArrayIndexOutOfBoundsException. A program may overrun an array boundary
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-11
V3.1
EXempty
without explicitly handling or throwing this exception. In this case, if it is thrown, the
exception percolates up to the JVM as an uncaught exception.
END OF LAB
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-12 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Reference Code
package lab8.model;
import java.util.Vector;
import java.io.*;
import lab8.model.reviewer.Reviewer;
public class Cupboard {
private static Vector testCollection = new Vector();
private static Vector personCollection = new Vector();
public static void init() {
String prefix = "C:\\OOPwJava\\lab8\\solution\\";
BufferedReader personReader = null;
try {
personReader = new BufferedReader(
new FileReader(prefix+"persons.txt"));
String name = null;
while ((name = personReader.readLine()) != null) {
String eMail = personReader.readLine();
String userId = personReader.readLine();
String password = personReader.readLine();
String privilege = personReader.readLine();
Person thePerson = null;
if (privilege.equals("USER")) {
thePerson = new Customer(name, eMail);
} else if (privilege.equals("DEVELOPER")) {
thePerson = new Developer(name, eMail);
} else if (privilege.equals("REVIEWER")) {
thePerson = new Reviewer(name, eMail);
}
thePerson.createProfile(userId, password);
Cupboard.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-13
V3.1
EXempty
personCollection.add(thePerson);
}
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(1);
} finally {
try {
if (personReader != null) {
personReader.close();
}
catch (IOException ioe2) {
}
}
BufferedReader testReader = null;
try {
testReader = new BufferedReader(
new FileReader(prefix+"tests.txt"));
String name = null;
while ((name = testReader.readLine()) != null) {
String area = testReader.readLine();
String status = testReader.readLine();
Test theTest = new Test(name, area);
theTest.setStatus(status);
testCollection.add(theTest);
}
testReader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(1);
} finally {
try {
if (testReader != null) {
testReader.close();
}
} catch (IOException ioe2) {
}
}
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-14 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
public static Person login(String theUserId,String thePassword) {
Person thePerson = null;
for (int index=0; index < personCollection.size(); index++) {
thePerson = (Person) personCollection.get(index);
if (thePerson.getProfile().getUserId().equals(theUserId)) {
break;
}
}
if (thePerson != null) {
boolean loggedIn = thePerson.login(theUserId, thePassword);
if (loggedIn) {
return thePerson;
}
}
return null;
}
public static void listTests(Person thePerson) {
String filter = "";
if (thePerson.getProfile().getPrivilege().
equals(Profile.DEVELOPER)) {
filter = Test.DEVELOPMENT;
} else if (thePerson.getProfile().getPrivilege().
equals(Profile.USER)) {
filter = Test.PRODUCTION;
} else if (thePerson.getProfile().getPrivilege().
equals(Profile.REVIEWER)) {
filter = "ALL";
}
for (int index = 0; index < testCollection.size(); index++) {
Test theTest = (Test) testCollection.get(index);
if (theTest.getStatus().equals(filter) ||
filter.equals("ALL")) {
System.out.println("\t" + theTest.getIdNumber() +
" : " + theTest.getName() + " : " + theTest.getArea());
}
}
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-15
V3.1
EXempty
}
package lab8.model;
public class Customer extends Person {
/**
* Constructor for Customer
*/
public Customer() {
super();
}
/**
* Constructor for Customer
*/
public Customer(String theName, String theEMail) {
super(theName, theEMail);
}
/**
* @see Person#createProfile(String, String)
*/
public void createProfile(String theUserId, String thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.USER);
setProfile(theProfile);
}
}
package lab8.model;
public class Developer extends Person {
/**
* Constructor for Developer
*/
public Developer() {
super();
}
/**
Customer.java
Developer.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-16 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
* Constructor for Developer
*/
public Developer(String theName, String theEMail) {
super(theName, theEMail);
}
/**
* @see Person#createProfile(String, String)
*/
public void createProfile(String theUserId, String thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.DEVELOPER);
setProfile(theProfile);
}
}
package lab8.driver;
import lab8.model.*;
public class Driver {
public static void main(String[] args) {
Cupboard.init();
Person someCustomer = Cupboard.login("ADAM", "ADAM123");
if (someCustomer != null) {
System.out.println("Welcome " +someCustomer.getName() +
" you logged in successfully");
Cupboard.listTests(someCustomer);
} else {
System.out.println("Sorry, access denied");
}
someCustomer = Cupboard.login("CHAR","CHAR321");
if (someCustomer != null) {
System.out.println("Welcome " +someCustomer.getName() +
" you logged in successfully");
Cupboard.listTests(someCustomer);
} else {
System.out.println("Sorry, access denied");
Driver.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-17
V3.1
EXempty
}
someCustomer = Cupboard.login("ED","ED456");
if (someCustomer != null) {
System.out.println("Welcome " +someCustomer.getName() +
" you logged in successfully");
Cupboard.listTests(someCustomer);
} else {
System.out.println("Sorry, access denied");
}
}
}
package lab8.model;
public abstract class Person {
private String name;
private String eMail;
private Profile profile;
/**
* Constructor for Customer
*/
public Person() {
super();
}
/**
* Create a new Customer from the specified parameters
* @param theName The name to set
* @param theEMail The eMail to set
*/
public Person(String theName, String theEMail) {
super();
setName(theName);
setEMail(theEMail);
}
/**
* Gets the name
* @return Returns a String
*/
Person.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-18 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
public String getName() {
return name;
}
/**
* Sets the name
* @param name The name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the eMail
* @return Returns a String
*/
public String getEMail() {
return eMail;
}
/**
* Sets the eMail
* @param mail The eMail to set
*/
public void setEMail(String mail) {
eMail = mail;
}
/**
* Gets the profile
* @return Returns a Profile
*/
public Profile getProfile() {
return profile;
}
/**
* Sets the profile
* @param profile The profile to set
*/
public void setProfile(Profile profile) {
this.profile = profile;
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-19
V3.1
EXempty
/**
* Log in with the specified user ID and password.
* @param theUserId User ID to use for the login request
* @param thePassword Password to use for the login request
* @return boolean True if login was a success.
*/
public boolean login(String theUserId, String thePassword) {
return profile.authenticate(theUserId, thePassword);
}
/**
* Create a profile for the Customer
* @param theUserId User ID of the customer
* @param thePasswork Password of the customer
*/
public abstract void createProfile(String theUserId, String thePassword);
}
package lab8.model;
public class Profile {
public final static String USER = "USER";
public final static String DEVELOPER = "DEVELOPER";
public final static String REVIEWER = "REVIEWER";
private String userId;
private String password;
private String privilege;
/**
* Constructor for Profile
*/
public Profile() {
super();
}
/**
* Create the Profile
* @param theUserId The user id to set
* @param thePassword The password to set.
*/
public Profile(String theUserId, String thePassword) {
super();
Profile.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-20 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
setUserId(theUserId);
setPassword(thePassword);
}
/**
* Gets the userId
* @return Returns a String
*/
public String getUserId() {
return userId;
}
/**
* Sets the userId
* @param userId The userId to set
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* Gets the password
* @return Returns a String
*/
public String getPassword() {
return password;
}
/**
* Sets the password
* @param password The password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Authenticate the user ID and password
* @param theUserId The user ID to be authenticated
* @param thePassword The password to be authenticated
* @return Returns true if the user ID and password are valid
*/
boolean authenticate(String theUserId, String thePassword) {
if (theUserId == null || thePassword == null) {
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-21
V3.1
EXempty
return false;
}
return (theUserId.equals(userId) &&
thePassword.equals(password));
}
/**
* Gets the privilege
* @return Returns a String
*/
public String getPrivilege() {
return privilege;
}
/**
* Sets the privilege
* @param privilege The privilege to set
*/
public void setPrivilege(String privilege) {
this.privilege = privilege;
}
}
package lab8.model.reviewer;
import lab8.model.Person;
import lab8.model.Profile;
public class Reviewer extends Person {
/**
* Constructor for Reviewer
*/
public Reviewer() {
super();
}
/**
* Constructor for Reviewer
*/
public Reviewer(String theName, String theEMail) {
Reviewer.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-22 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
super(theName, theEMail);
}
/**
* @see Person#createProfile(String, String)
*/
public void createProfile(String theUserId, String thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.REVIEWER);
setProfile(theProfile);
}
}
package lab8.model;
public class Test {
public final static String DEVELOPMENT = "DEVELOPMENT";
public final static String PRODUCTION = "PRODUCTION";
private static int nextTestIdNumber = 1;
private String status;
private String area;
private String name;
private int idNumber;
/**
* Constructor for Test
*/
public Test() {
super();
}
/**
* Constructor for Test.
* @param theName Test name
* @param theArea Test area
*/
public Test(String theName, String theArea) {
setName(theName);
setArea(theArea);
setIdNumber(getNextTestIdNumber());
Test.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-23
V3.1
EXempty
}
/**
* Gets the area
* @return Returns a String
*/
public String getArea() {
return area;
}
/**
* Sets the area
* @param area The area to set
*/
public void setArea(String area) {
this.area = area;
}
/**
* Gets the name
* @return Returns a String
*/
public String getName() {
return name;
}
/**
* Sets the name
* @param name The name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the idNumber
* @return Returns a int
*/
public int getIdNumber() {
return idNumber;
}
/**
* Sets the idNumber
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-24 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
* @param idNumber The idNumber to set
*/
public void setIdNumber(int idNumber) {
this.idNumber = idNumber;
}
/**
* Get the next test id
* @return next test id
*/
private static int getNextTestIdNumber() {
return nextTestIdNumber++;
}
/**
* Gets the status
* @return Returns a String
*/
public String getStatus() {
return status;
}
/**
* Sets the status
* @param status The status to set
*/
public void setStatus(String status) {
this.status = status;
}
}
V3.1
backpg
Back page

Student Exercises
V3.1
TOC
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Contents iii
Contents
Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v
Case Study Description. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii
Exercise 1. Hello World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1
Exercise 2. Java Language Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1
Exercise 3. Using Existing Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1
Exercise 4. Creating Your Own Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1
Exercise 5. Class Methods and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-1
Exercise 6. Object Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1
Exercise 7. Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-1
Exercise 8. Simple I/O and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-1
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
iv Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Trademarks v
V1.2.2
LSGp
Trademarks
The reader should recognize that the following terms, which appear in the content of this
training document, are official trademarks of IBM or other companies:
IBM is a registered trademark of International Business Machines Corporation.
The following are trademarks of International Business Machines Corporation in the United
States, or other countries, or both:
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the
United States, other countries, or both.
Microsoft, Windows and Windows NT are trademarks of Microsoft Corporation in the
United States, other countries, or both.
Pentium is a trademark of Intel Corporation in the United States, other countries, or both.
UNIX is a registered trademark of The Open Group in the United States and other
countries.
Linux is a registered trademark of Linus Torvalds in the United States and other countries.
Other company, product and service names may be trademarks or service marks of others.
AIX CICS ClearCase
DB2 Everyplace IMS
OS/390 Rational VisualAge
WebSphere
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
vi Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Case Study Description vii
V3.1
pref
Case Study Description
Certification Unlimited Partnership (CUP) would like to develop a Web-based application
for their Distant Exam Delivery System (DEDS). Currently CUP has many certification
exams for computing professionals to take to be CUP-certified in various fields of study.
Currently to become certified, a test taker (customer) must travel to a designated CUP
testing site and take a written, paper-based, certification test. This test must then be scored
and the results communicated back to the customer.
CUP would like DEDS to be able to allow their customers to complete their certification
exams via the Web. This system should allow people to register to become customers for
the service and allow them to update their profile. A customer would be allowed to select a
specific exam to take (after signing in to the system). Upon completion of the exam, the
results will be graded, and a score report will be delivered to the customer immediately.
Statistics on exam takers and their scores are kept for the purposes of verification,
reporting, exam effectiveness analysis, and so forth.
The generated exam will be a random collection of questions pulled from the selected tests'
pool of questions. Questions are categorized into test categories. This permits the random
generation of exams which all are representative of all major areas of coverage of a test.
Further, exam score reports provide grades on the questions within each category
(subscores) to help a candidate better understand their areas of strengths and
weaknesses.
The system needs to be built to manage customer, test and exam data. In particular,
customer data will include registration, exam transcripts and certification completion
information. Test data will include question and answer pools for both production exams
and exams under review.
Customers register with the system to specify a unique user name and password. They will
log in to take exams or to review their status (certification completion). Customers can also
obtain a transcript of previously taken exams (with scores).
Test developers should also be able to submit new tests and/or questions for review as well
as be able to perform maintenance on existing tests and questions.
CUP also needs a way for Subject Matter Experts (SMEs) to take the complete review
exam and add comments on each question.
Administration staff need to perform a series of analysis tasks including Customer analysis
(for example, demographics, progress toward certification, and so forth), Test analysis (for
example, performance measures on questions, sub score areas, and tests); test
maintenance (for example, promoting reviewed exams to production and fixing questions);
and interaction with other systems (for example, publishing reviewed exams to an external
testing service).
CUP would like this system to enhance their customer service and also integrate their
various business processes (test creation, test review, exam delivery, exam scoring,
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
viii Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
customer record management, customer analysis, test analysis, and test maintenance).
The DEDS system should also be flexible to support future business processes associated
with their certification exam business.
End of Case Study
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 1. Hello World 1-1
V3.1
EXempty
Exercise 1. Hello World
What This Exercise Is About
This exercise is intended to introduce you to Java. You may already
have a background in procedural programming. This exercise will
show you some aspects of the new language on familiar territory. You
will enter source code into a file, compile it, and execute it using the
javac.exe compiler and the java.exe virtual machine.
What You Should Be Able to Do
At the end of the lab, you should be able to:
Write Java source code using Windows Notepad as an editor
Use javac.exe to compile the source code to bytecode
Use java.exe to run the bytecode
Learning Strategy
Individual exercise
Required Materials
Sun J2SE SDK 1.4.2
Windows Notepad or equivalent
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
1-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Exercise Instructions
You have heard about the compiler and JVM. You're familiar with COBOL, PL/I or some
other procedural language. This exercise introduces you to Java by having you write,
compile, and run a short procedural Java program.
Directions
Any text editor will work for this exercise. These instructions refer to Windows Notepad
when a text editor is being referenced. You will use a text editor to write a simple Java
program. You will compile the program using the javac command from the SDK. The java
command will run the program.
Step A: Write the Source Code
1. Create directories C:\OOPwJava\lab1 if they dont already exist.
2. Create a new source file in Notepad.
a. Open Notepad by selecting Start -> Run... from the task bar.
b. Type notepad in the Open: field of the Run dialog, and click OK.
3. Create a new public class, HelloWorld, with a main method. The main method should
output the string Hello, World!.
a. Enter the following source code:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
4. Save the file as c:\OOPwJava\lab1\HelloWorld.java.
Step B: Compile the Source Code
1. Open a command window.
a. Select Start -> Run... from the task bar.
b. Type cmd in the Open: field of the Run dialog, and click OK.
2. In the new cmd window, enter the command cd c:\OOPwJava\lab1.
3. Type javac HelloWorld.java in the cmd window to compile the source code.
4. If there are any syntax errors, fix them in your HelloWorld.java source file and recompile
the program.
5. Type dir to see the files in this directory. You should see two:
a. HelloWorld.java is the source file you edited above.
b. HelloWorld.class is the byte code for the HelloWorld class.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 1. Hello World 1-3
V3.1
EXempty
Step C: Execute the Result
1. Enter java HelloWorld to execute the bytecodes of the class in a new JVM.
a. You should see the text Hello, World! displayed in the cmd window.
b. If there are any run time errors you will need to fix them, recompile, and then rerun
your program.
c. You can now close the cmd window by typing exit.
Summary
You have written, compiled, and run a simple procedural Java program using a text editor
and the SDK. Writing and executing a Hello World program is the traditional introduction
into many languages. Java is an object-oriented language. You wrote a short procedural
program, but it had to exist within a class. When you learn Java language syntax, you will
create your own classes and begin to compose object-oriented programs.
END OF LAB
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
1-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Sample Output
Hello, World!
Reference Code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
File: HelloWord.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 2. Java Language Syntax 2-1
V3.1
EXempty
Exercise 2. Java Language Syntax
What This Exercise Is About
This exercise gives you practice using the non-OO, or procedural side
of Java. You will code all of this exercise in a single main() method of a
Driver class.
In this exercise you will continue your development of Java source
code within Notepad, compile your code with javac, and run your
code with java.
What You Should Be Able to Do
At the end of the lab, you should be able to:
Use some primitive data types and statements addressed in Java
Use the commonly-used operators addressed in Java
Write a simple Java program
Required Materials
Sun J2SE SDK 1.4.2
Windows Notepad or equivalent
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
2-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Exercise Instructions
This exercise is carried out entirely using the Suns J2SE SDK 1.4.2.
For this and all subsequent exercises, you may use any text editor that you choose
(notepad, wordpad, one that you may download from the Internet). However, the
instructions for this, and all future exercises, assume that you are using a simple text editor
like notepad. From now on, we will use the generic term "the editor" to refer to your text
editor of choice. You will compile and execute your programs from the command line
prompt using javac.
You will create a Java class called Driver that will hold a single public static void
main(String[ ]) method. All of the executable code for this exercise will be put in the main()
method. The main() method will contain an array of test scores for which some statistics will
be computed. You will create this array and code the arithmetic mean and the standard
deviation of these scores, displaying the values on the console.
You will need to create an array of doubles which you will call testScores, and then access
it with looping and conditional statements. The four fundamental arithmetic operators will
need to be used. Strings and the concatenation operator will aid you in creating the display
data.
Directions
Step A: Create a Driver Class with a Main Method.
1. Change to the C:\OOPwJava\lab2 directory.
2. Using the editor create a new public class called Driver with an empty public static
void main(String[ ]) method. Our solution is as follows:
public class Driver {
public static void main(String[] args) {
}
}
3. Save the file as Driver.java in the C:\OOPwJava\lab2 directory.
Step B: Create the Data
1. In the main method, define a reference to an array of doubles; named testScores, two
doubles; named totalScore and meanScore, and an int; named index. Our solution is as
follows:
double[] testScores = { 16.0, 22.0, 24.0, 24.0, 27.0,
28.0, 29.0, 30.0 };
int testCount = testScores.length; // number of scores
double totalScore = 0.0;
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 2. Java Language Syntax 2-3
V3.1
EXempty
double meanScore = 0.0;
int index;
Step C: Compute and Display the Arithmetic Mean of the Scores
1. Sum the scores stored in the array, testScores, and then divide by the number of
scores. Store the arithmetic mean in the variable meanScore. Our solution follows:
// Compute the mean (arithmetic average) test score
for (index = 0; index < testCount; index++) {
totalScore = totalScore + testScores[index];
}
meanScore = totalScore / testCount;
2. Display the mean along with simple explanatory text. Use
System.out.println(String) to display text on the console. Our solution follows:
System.out.println("The arithmetic mean is " + meanScore);
Note: The "+" operator is the concatenation operator for Strings.
Step D: Compute and Display the Standard Deviation of the Scores
1. For each score, compute the square if it's different from the mean. Sum these squares
in a variable. Don't worry about the sign of the difference, the squaring operation will
make all terms positive. Our solution is as follows:
double sum = 0.0;
for (index = 0; index < testCount; index++) {
// Compute each score's difference from the mean
double distFromMean = testScores[index] - meanScore;

// Accumulate its square
double distFromMeanSquared = distFromMean * distFromMean;

sum += distFromMeanSquared;
}
2. Compute the arithmetic mean of the sum. Our solution is as follows:
double meanOfSquares = sum / testCount;
3. Take the square root of the result to obtain the standard deviation. Use the
Math.sqrt(double) function. Our solution is as follows:
double stdDeviation = Math.sqrt(meanOfSquares);
4. Display the standard deviation along with explanatory text. Our solution is as follows:
System.out.println("The standard deviation is " +
stdDeviation);
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
2-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
5. Save source file for the Driver class.
Step E: Test the Program
1. Compile your Driver.java source file. Fix any errors that the compilation may identify.
a. From within a command prompt window, execute the following command:
javac Driver.java
2. Run your Driver class.
a. From within the same command prompt window, execute the following command:
java Driver
Summary
Your two display statements should display the mean and standard deviation, respectively.
If you use the test score values shown in the hints in step B, you should get a mean of 25.0,
and a standard deviation of 4.2720.
You used arithmetic, assignment, and concatenation operators in this exercise. You
initialized an array of literal primitive double values and then accessed the array to perform
computations on its contents. You coded two loops to carry this out. You used a Math
method and a System print method without understanding their meaning. You will learn
these things later.
END OF LAB
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 2. Java Language Syntax 2-5
V3.1
EXempty
Reference Code:
public class Driver {
public static void main(java.lang.String[] args) {
double[] testScores = {16.0, 22.0, 24.0, 24.0, 27.0, 28.0, 29.0,
30.0};
int testCount = testScores.length; // number of scores
double totalScore = 0.0;
double meanScore = 0.0;
int index;
//Compute the mean (arithmetic average) test score
for (index = 0; index < testCount; index++) {
totalScore = totalScore + testScores[index];
}
meanScore = totalScore / testCount;
System.out.println("The arithmetic mean is " + meanScore);
double sum = 0.0;
for (index = 0; index < testCount; index++) {
//Compute each score's difference from the mean
double distFromMean = testScores[index] - meanScore;
//Accumulate its square
distFromMean = distFromMean * distFromMean;
sum += distFromMean;
}
double meanOfSquares = sum / testCount;
double stdDeviation = Math.sqrt(meanOfSquares);
System.out.println("The standard deviation is " + stdDeviation);
}
}
Driver.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
2-6 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 3. Using Existing Classes 3-1
V3.1
EXempty
Exercise 3. Using Existing Classes
What This Exercise Is About
Java comes with many classes already defined. This exercise
introduces you to some of those classes. You will learn how to use
them and, by extension, other classes defined in Java.
What You Should Be Able to Do
At the end of the lab, you should be able to:
Instantiate objects
Send messages to objects
Receive return values from message sends
Use the main features of the String and Vector classes
Required Materials
Sun J2SE SDK 1.4.2
Windows Notepad or equivalent
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
3-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Exercise Instructions
We shall use the term JVM as an abbreviation for Java virtual machine in the directions.
We shall refer to Software Development Kit as SDK.
You will create a class called Driver that will define a public static void main(String[])
method. All the executable code that you will write in this exercise will be within this main()
method.
In the scenario for this exercise you will:
Accept test statistics (corresponding name and score pairs) from the command line.
Validate number of parameters passed in.
Parse and store each parameter in a vector.
Find the high and low score.
Print the name and score pair that corresponds to the high and low scores.
Directions
Step A: Driver Class, and Main Method
1. Change to the C:\OOPwJava\lab3 directory.
2. Using the editor create a new public class called Driver with an empty public static
void main(String[ ]) method. Our solution is as follows:
public class Driver {
public static void main(String[] args) {
}
}
3. Save the file as Driver.java in the C:\OOPwJava\lab3 directory.
Step B: Validate the Command-Line Arguments
1. If there are no command-line arguments detected, display an explanatory message that
the arguments should be name/score pairs and then exit. The command line arguments
are passed in via the String[ ] args parameter for the main() method.
Hint: the expression args.length evaluates to the number of arguments.
Hint: a statement of the form System.exit(int); terminates the JVM.
Our solution is as follows:
if (args.length == 0) {
System.out.println("Please pass test statistics on the command line.");
System.out.println("Format: name1 score1 name2 score2 ...");
System.exit(1);
}
2. Display an explanatory message and exit if the number of command-line parameters is
odd (The parameters should be a sequence of name/score pairs.).
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 3. Using Existing Classes 3-3
V3.1
EXempty
Hint: Using the remainder operator, %, will allow you to determine if an int is even or
odd. someInt % 2 evaluates to 0 if someInt contains an even number.
Our solution is as follows:
if ((args.length % 2) > 0) {
System.out.println("Must have even number of arguments");
System.out.println("Format: name1 score1 name2 score2 ...");
System.exit(1);
}
Step C: Insert Each Parameter Value Into its Corresponding Instance of
Java.Util.Vector
1. Create a reference to a java.util.Vector. Label it names. Initialize it to be a new empty
java.util.Vector. This vector will hold the collection of names passed on the command
line.
Hint: new SomeClass() creates an instance of SomeClass using the no-argument
constructor.
Our solution is as follows:
java.util.Vector names = new java.util.Vector();
2. Create another reference to a java.util.Vector. Label it scores. It will hold the collection
of scores passed on the command line. The position of each score element in the
scores vector will correspond to the position of each name element in the names
vector after you populate the vectors.
Our solution is as follows:
java.util.Vector scores = new java.util.Vector();
3. Copy each command-line argument to its corresponding vector. That is, a name
argument should be added to the names vector, while a score argument should be
added to the scores vector.
Hint: name strings and score strings are alternating elements of the String[] args
String array parameter of main().
Hint: the add method of java.util.Vector appends an Object reference to the end of its
vector.
Hint: the expression args.length evaluates to the number of command line
parameters.
Hint: the expression index++ increments the contents of an index int variable after it is
used in an expression.
Hint: a while(expression) { } loop enters each iteration of its body only while
expression evaluates to true.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
3-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Our solution is as follows:
int index = 0;
while (index < args.length) {
names.add(args[index++]);
scores.add(args[index++]);
}
Step D: Find the Element Indices of the High and Low Scores
1. Create int variables named hiScoreIndex and loScoreIndex. Initialize them to 0.
These will contain the indices of the high score and low score within the vectors.
2. Create int variables named hiScore and loScore. Initialize hiScore to 0. Initialize
loScore to be the largest possible int value, Integer.MAX_VALUE.
3. Examine each element of the scores vector. Use the Integer class to access the String
value as an int value. Conditionally update hiScore or loScore scores as you
encounter each element. Whenever you update either variable, store the current
element index in hiScoreIndex or loScoreIndex as appropriate.
Hint: the size() method of java.util.Vector returns the number of elements stored in the
vector.
Hint: the get(int) method of java.util.Vector returns an element stored in the vector at
an int, zero-based, offset.
Hint: convert a numeric String value to an int using this form: Integer.parseInt(String);
Here is our solution:
int hiScoreIndex = 0;
int lowScoreIndex = 0;
int lowScore =Integer.MAX_VALUE;
int hiScore = 0;
for (index = 0; index < scores.size(); index++) {
//Get the score string
String scoreString = (String) scores.get(index);
//Convert scoreString to an int
int score = Integer.parseInt(scoreString);
// Accumulate index of low and high scores
if (score < lowScore) {
lowScoreIndex = index;
lowScore = score;
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 3. Using Existing Classes 3-5
V3.1
EXempty
if (score > hiScore) {
hiScoreIndex = index;
hiScore = score;
}
}
Step E: Display the Results
1. Display the high-scoring persons name and score. Use String concatenation to present
a meaningful sentence.
Hint: use get(int) on each vector, passing the corresponding low or high score index.
2. Display the low-scoring persons name and score. Again use String concatenation to
present a meaningful sentence.
Our solution is as follows:
//Print results
System.out.println("High scorer was " + names.get(hiScoreIndex) +
" with a score of " + scores.get(hiScoreIndex));
System.out.println("Low scorer was " + names.get(lowScoreIndex) +
" with a score of " + scores.get(lowScoreIndex));
3. Save the source file for the Driver class.
Step F: Test the Program
1. Compile your Driver.java source file. Fix any errors that the compilation may identify.
a. From within a command prompt window, execute the following command:
javac Driver.java
2. Run your Driver class.
a. From within the same command prompt window, execute the following command:
java Driver Adam 18 Bob 23 Charlene 19 Doug 20 Elaine 21
3. Check the output for correct results. The values "Adam 18 Bob 23 Charlene 19 Doug 20
Elaine 21" should yield a display with values like these:
High scorer was Bob with a score of 23
Low scorer was Adam with a score of 18
4. Try varying parameters to test your initial test conditions.
Summary
In this exercise you passed name-score test statistics on the command line. You validated
the existence of parameters, and if there was an even number of them, and whether there
was an even number of them. You extracted the parameters from the argument array of the
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
3-6 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
main method, storing each in a corresponding java.util.Vector instance. You examined
each score to find the high and low score index. You used that index to display the name
and score of the high and low scoring persons. Finally, you printed the name and score pair
that corresponded to the high and low scores.
You practiced using existing classes, including a wrapper class. You used methods of the
java.lang.System class to exit the JVM and to display results. You instantiated classes,
sent messages to instances, and received results. In the course of completing this exercise
you became more familiar with main features of the String, Vector, and wrapper classes.
END OF LAB
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 3. Using Existing Classes 3-7
V3.1
EXempty
Reference Source Code
Class Driver
package lab3;
public class Driver {
public static void main(java.lang.String[] args) {
if (args.length == 0) {
System.out.println("Please pass test statistics on the command line.");
System.out.println("Format: name1 score1 name2 score2 ...");
System.exit(1);
}
if ((args.length % 2) > 0) {
System.out.println("Must have even number of arguments");
System.out.println("Format: name1 score1 name2 score2 ...");
System.exit(1);
}
java.util.Vector names = new java.util.Vector();
java.util.Vector scores = new java.util.Vector();
int index = 0;
while (index < args.length) {
names.add(args[index++]);
scores.add(args[index++]);
}
int hiScoreIndex = 0;
int lowScoreIndex = 0;
int lowScore = Integer.MAX_VALUE;
int hiScore = 0;
for (index = 0; index < scores.size(); index++) {
//Get the score string
String scoreString = (String) scores.get(index);
//Convert scoreString to an int
int score = Integer.parseInt(scoreString);
// Accumulate index of low and high scores
if (score < lowScore) {
lowScoreIndex = index;
lowScore = score;
}
if (score > hiScore) {
hiScoreIndex = index;
hiScore = score;
}
}
//Print results
Driver.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
3-8 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
System.out.println(
"High scorer was "
+ names.get(hiScoreIndex)
+ " with a score of "
+ scores.get(hiScoreIndex));
System.out.println(
"Low scorer was "
+ names.get(lowScoreIndex)
+ " with a score of "
+ scores.get(lowScoreIndex));
}
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-1
V3.1
EXempty
Exercise 4. Creating Your Own Classes
What This Exercise Is About
You will create three classes used to authenticate a customer who
wishes to access a test using an online exam delivery system (OEDS).
The UML class diagram shown below depict the classes that you will
create in this exercise.
Customer
-name : String
-eMail : String
-profile : Profile
+Customer()
+Customer(String,String)
+getEMail() : String
+getName() : String
+getProfile() : Profile
+login(String, String) : boolean
+setEmail(String) : void
+setName(String) : void
+setProfile(Profile) : void
ProfiIe
-userid : String
-password : String
+Profile() :
+Profile(String,String) :
+authenticate(String,String) : boolean
+getPassword() : String
+getUserid() : String
+setPassword(String) : void
+setUserid(String) : void
Driver
+main(String[]) : void
1
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
What You Should Be Able to Do
At the end of the lab, you should be able to:
Create your own class
Create instance variables
Create methods
Create constructors
Create accessors
Learning Strategy
Individual exercise
Required Materials
Sun J2SE SDK 1.4.2
Windows Notepad or equivalent
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-3
V3.1
EXempty Exercise Instructions
You will code the appropriate constructors, methods, instance variables, and accessors for
the classes shown in the UML class diagram. The Customer class represents a customer
of OEDS. A customer has name and e-mail address attributes. It also has an associated
instance of a Profile class. A Profile has user ID and password attributes. You will code a
main method for the Driver class that will instantiate a Customer and its associated Profile
instance. You will then ask the Customer instance to log in a user having supplied user ID
and password. Finally, you will display the results.
Directions
Step A: Create the Package, Driver Class, and Main Method
1. Create a lab4 subdirectory of C:\OOPwJava. Switch to that subdirectory.
2. Using the editor create a new public class called Driver with an empty public static
void main(String[ ]) method. Our solution is as follows:
public class Driver {
public static void main(String[] args) {
}
}
3. Save the file as Driver.java in the C:\OOPwJava\lab4 directory.
4. You will come back and add code to the main(String[ ]) method of the Driver class in a
future step.
Step B: Create the Customer Class, Fields, and Accessor Methods
This step will create the basics of the Customer class: the class definition, the initial
instance variables (fields), and their accessor methods. At this point, you will let the
compiler synthesize the default constructor for you.
1. Refer to the UML class diagram to see the Customer class.
2. Using the editor, define the Customer class within the lab4 package.
3. Define a private field name of type String in the class definition:
private String name;
4. Define the public getter method for this field:
public String getName() {
return name;
}
5. Define the public setter:
public void setName(String newName) {
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
name = newName;
}
6. Using a similar approach, define another private field eMail of type String.
7. Define a public getter and setter for the eMail field, similar to what you did for the name
field.
8. Add one more private field, profile, of type Profile. Since this Customer class isn't being
compiled yet, it doesn't matter that the Profile class is still undefined.
9. Define a public getter and setter for the profile field, similar to what you did for the name
and eMail fields. Remember the return type of a method must match the data type of
the returning value.
10. Save the file in the lab4 subdirectory as Customer.java. Do not compile yet.
Step C: Create the Profile Class, Fields, and Accessor Methods
Using the same approach as used in defining the Customer class, define the Profile class:
the class definition, the initial instance variables (fields), and their accessor methods.
Again, you will let the compiler synthesize the default constructor for you.
1. Refer to the UML class diagram to see the Customer class.
2. Using the editor, define the Profile class within the lab4 package.
3. Define a private field userId of type String in the class definition:
private String userId;
4. Define the public getter method for this field:
public String getUserId() {
return userId;
}
5. Define the public setter:
public void setUserId(String newUserId) {
userId = newUserId;
}
6. Using a similar approach, define another private field password of type String.
7. Define a public getter and setter for the password field, similar to what you did for the
userId field.
8. Save the file in the lab4 subdirectory as Profile.java. Do not compile yet.
Step D: Test the Customer and Profile Classes
In this step, you will create an instance of the Customer class, and an instance of the
Profile class. You will then associate the profile with the customer. You will then print
information about the customer and profile to the Console window.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-5
V3.1
EXempty
1. Modify the main(String[ ]) method of the Driver class in directory lab4 to create an
instance of Customer and store a reference to the instance in a variable called
theCustomer.
a. Use the editor to open the Driver.java file. Scroll down to the main(String[ ])
method declaration.
b. Within the main(String[ ]) method declaration, enter the Java code to create an
instance of the Customer class and store it into a variable named theCustomer.
The code should look like:
Customer theCustomer = new Customer();
c. After that line, send the message setName(String) to theCustomer passing Adam
as the parameter.
The code should look like:
theCustomer.setName("Adam");
d. Send the message setEMail(String) to theCustomer passing
"adam@hotmail.com" as the parameter (sample code omitted).
e. Use System.out.println(String) to print the theCustomer's information out to the
Console window.
The code should look like:
System.out.println(
"The customer's name is: "
+ theCustomer.getName()
+ ", and eMail address is: "
+ theCustomer.getEMail());
Information: Remember that white space is irrelevant, this line of code could exist
all on one line. The formatting above is done simply to make the code more
readable within this exercise.
f. Save the file as Driver.java again.
g. Since the Driver class refers to the Customer and Profile class, compiling Driver will
also force the compilation of Customer and Profile.
Information: This applies as long as a compiled .class file does not exist, or, if one
exists, that the timestamp on the source .java file is later than the one on the
associated .class file.
Compile Driver.java in the lab4 directory: Open a command prompt window and
enter:
C:\OOPwJava\lab4> javac Driver.java
Fix any errors in any of the three classes, and recompile.
h. Execute the Driver class from the command prompt window:
C:\OOPwJava\lab4> java Driver
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-6 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
i. The following text should display in the window:
The customer's name is: Adam, and eMail address is:
adam@hotmail.com
2. Create an instance of Profile and store a reference to the instance in a variable called
theProfile.
a. Immediately before the System.out.println() statement in the Driver class, create
an instance of Profile and store it's reference in a variable called theProfile.
b. Send the message setUserId(String) to theProfile passing ADAM as the
parameter.
c. Send the message setPassword(String) to theProfile passing "ADAM123" as the
parameter.
d. After the other System.out.println() statement, use another
System.out.println(String) statement to print the theProfile's information out to the
Console window.
e. The code within your main(String[ ]) method for the Driver class should look like
the following:
Customer theCustomer = new Customer();
theCustomer.setName("Adam");
theCustomer.setEMail("adam@hotmail.com");
Profile theProfile = new Profile();
theProfile.setUserId("ADAM");
theProfile.setPassword("ADAM123");
System.out.println(
"The customer's name is: "
+ theCustomer.getName()
+ ", and eMail address is: "
+ theCustomer.getEMail());
System.out.println(
"The profile's userId is: "
+ theProfile.getUserId()
+ ", and the password is: "
+ theProfile.getPassword());
f. Save your file again as Driver.Java.
g. From the command prompt window, compile and execute Driver.
h. The following text should be displayed in the window:
The customer's name is: Adam, and eMail address is:
adam@hotmail.com
The profile's userId is: ADAM, and the password is: ADAM123
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-7
V3.1
EXempty
Step E: Associate a Profile with a Customer
In this step you will associate the instance of profile with the instance of customer. You will
then see how you can access the profile through the customer.
1. Modify the main(String[ ]) method so that after the instance of Profile is created and
initialized, the setProfile(Profile) method of Customer is called to associate theProfile
with theCustomer.
a. After the theProfile.setPassword("ADAM123"); statement send the
setProfile(Profile) message to theCustomer passing theProfile as the parameter.
Our solution looks like this:
theCustomer.setProfile(theProfile);
2. Modify the output of the theProfile's information. Rather than directly referencing the
theProfile variable, modify the code so that it accesses the instance of Profile
associated with theCustomer via the getProfile() message.
3. In the System.out.println() statement for printing theProfile's information change
"theProfile" to be "theCustomer.getProfile()".
a. Our solution looks like this:
System.out.println(
"The profile's userId is: "
+ theCustomer.getProfile().getUserId()
+ ", and the password is: "
+ theCustomer.getProfile().getPassword());
Information: This is called message chaining. The getProfile() message is sent to
theCustomer, the instance of Profile that is associated with theCustomer is
returned, then the message getUserId() is sent to this instance of Profile.
Functionally the two are equivalent, but with this option you no longer need to retain
a reference to the profile after it is associated with the customer.
b. Save the file. Compile and execute Driver.
c. The same information that was previously displayed should appear in the window.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-8 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Step F: Create Constructors for Customer and Profile Classes
If you look at the Java code within the main(String[ ]) method of the Driver class, you have
written a lot of code to initialize the instances of Customer and Profile. You will add some
new methods to the Customer and Profile classes that will enable us to initialize the
variables without having to do it manually. These methods are called constructors.
1. Add a public constructor to the Customer class that will take two parameters, the
name, and the eMail. Initialize the name field to be the name passed in, and the eMail
field to be the eMail passed in.
a. Use the editor to open the Customer.java file in the lab4 directory.
b. Add the code to declare a new public constructor that passes a name and an eMail:
public Customer (String theName, String theEMail) {
}
2. Add the code to the Customer(String, String) constructor (between the curly brackets)
to send the setName(String) and setEMail(String) messages passing theName and
theEMail as parameters.
Our solution looks like:
setName(theName);
setEMail(theEMail);
3. Save the Customer class source.
4. Add a constructor to the Profile class that will take two parameters, the userId, and the
password. Initialize the userId field to be the userId passed in, and the password field
to be the password passed in.
a. Use the editor to open the Profile.java file in the lab4 directory.
b. Add the code to declare a new public constructor that passes a userid and a
password. In the constructor body, send the setUserId(String) and
setPassword(String) messages passing the new userId and password as
parameters:
public Profile(String theUserId, String thePassword) {
setUserId(theUserId);
setPassword(thePassword);
}
5. Save the Profile class source.
Step G: Modify Driver's Main(string[ ]) Method to Use the New
Constructors
In this step you will modify the main(String[ ]) to use the two constructors you created in
the previous step.
1. Modify the statement that creates the instance of Customer to use the two-argument
constructor. Remove the two set statements for name and eMail.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-9
V3.1
EXempty
Our solution looks like:
Customer theCustomer = new Customer("Adam",
"adam@hotmail.com");
a. Delete the two statements that send the setName() and setEMail() messages to
theCustomer.
2. Modify the statement that creates the instance of Profile to use the two argument
constructor. Remove the two "set" statements for userId and password.
Our solution looks like:
Profile theProfile = new Profile("ADAM", "ADAM123");
a. Delete the two statements that send the setUserId() and setPassword() messages
to theProfile.
3. Save the file. Compile and execute Driver.
4. You should get the same information in the window as before.
Step H: Create the Login and Authenticate Methods
So far all of our methods for the Customer and Profile classes have been dealing with
setting data, getting data or initializing data. Now you will add some actual business
functionality. You will add a login() method to Customer that will allow us to authenticate
the customer. The purpose of the Profile class is to authenticate customers (validate their
user id and password).
1. Add the authenticate(String, String) method to the Profile class. This method will
have a return type of boolean.
a. Open the Profile.java file within the lab4 directory.
b. Write the source code for the authenticate(String, String) method. The method
should return true if the provided userId and password (the two parameters) match
the Profile's userId and password, otherwise it will return false.
i. Test to see if theUserId is equal to userId AND thePassword is equal to
password.
Our solution looks like:
public boolean authenticate(String theUserId, String
thePassword) {
return ((theUserId.equals(userId)) &&
(thePassword.equals(password)));
}
c. Save the file as Profile.java.
2. Add the method login(String, String) method to the Customer class. This method will
have a return type of boolean.
a. Select the Customer.java file within the lab4 directory.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-10 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
b. Write the source code for the login(String, String) method. The method should
send the message authenticate(String, String) to the customer's profile and return
the result.
Our solution looks like:
public boolean login(String theUserId, String thePassword) {
return profile.authenticate(theUserId, thePassword);
}
3. Save the file as Customer.java.
Step I: Modify Driver's Main(string[ ]) Method to Log the Customer In.
In this step you will create another customer and profile. You will log the first customer in
and verify that the login was successful. You will then log the second customer in, using an
incorrect password, and verify that the login was unsuccessful.
1. Remove the System.out.println() statements of the main(String[ ]).
2. Where the System.out.println() statements were removed, create a boolean variable
called loginSuccessful and initialize it to false.
3. Send the login(String, String) message, using the correct values, to theCustomer
and assign the result into the loginSuccessful variable.
4. Using a simple if statement print the result out to the Console identifying the customer's
name, and whether the login was successful.
5. Create a new Customer; assign it to a variable called anotherCustomer.
6. Create a new Profile; assign it to a variable called anotherProfile.
7. Set the profile of anotherCustomer to be anotherProfile.
8. Send the login(String, String) message, using incorrect values, to anotherCustomer
and assign the result into the loginSuccessful variable.
9. Print the result to the Console identifying the customer's name, and whether or not the
login was successful.
10. Our solution looks like (the complete main(String[ ]) method text):
Customer theCustomer = new Customer("Adam", "adam@hotmail.com");
Profile theProfile = new Profile("ADAM", "ADAM123");
theCustomer.setProfile(theProfile);
boolean loginSuccessful = false;
loginSuccessful = theCustomer.login("ADAM", "ADAM123");
if (loginSuccessful)
System.out.println(theCustomer.getName() + " logged in
successfully");
else
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-11
V3.1
EXempty
System.out.println(theCustomer.getName() + " did not log in
successfully");
Customer anotherCustomer = new Customer("Charlene",
"char@email.com");
Profile anotherProfile = new Profile("CHAR", "CHAR321");
anotherCustomer.setProfile(anotherProfile);
loginSuccessful = anotherCustomer.login("CHAR",
"WRONGPASSWORD");
if (loginSuccessful)
System.out.println(anotherCustomer.getName() + " logged in
successfully");
else
System.out.println(anotherCustomer.getName() + " did not log
in successfully");
11. Save the file as Driver.java. Compile the three classes: Driver, Customer, and Profile.
Execute Driver.
12. The window should display:
Adam logged in successfully
Charlene did not log in successfully
Summary
This was an exercise in coding Java classes and their four essential ingredients:
constructors, methods, instance variables (also called fields or attributes), and access
methods (also called getters and setters, or accessors). You learned to encapsulate
instance data with accessor methods such that clients of a class could access that data
through a method call on the instance of the class. You also began to use practical Java
coding skills.
END OF LAB
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-12 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Reference Classes
public class Driver {
public static void main(java.lang.String[] args) {
Customer theCustomer = new Customer("Adam", "adam@hotmail.com");
Profile theProfile = new Profile("ADAM", "ADAM123");
theCustomer.setProfile(theProfile);
boolean loginSuccessful = false;
loginSuccessful = theCustomer.login("ADAM", "ADAM123");
if (loginSuccessful)
System.out.println(theCustomer.getName() + " logged in
successfully");
else
System.out.println(theCustomer.getName() + " did not log in
successfully");
Customer anotherCustomer = new Customer("Charlene", "char@email.com");
Profile anotherProfile = new Profile("CHAR", "CHAR321");
anotherCustomer.setProfile(anotherProfile);
loginSuccessful = anotherCustomer.login("CHAR", "WRONGPASSWORD");
if (loginSuccessful)
System.out.println(anotherCustomer.getName() + " logged in
successfully");
else
System.out.println(anotherCustomer.getName() + " did not log in
successfully");
}
}
public class Customer {
private String name;
private String eMail;
private Profile profile;
public Customer(String theName, String theEMail) {
setName(theName);
Driver.java
Customer.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-13
V3.1
EXempty
setEMail(theEMail);
}
public String getEMail() {
return eMail;
}
public String getName() {
return name;
}
public Profile getProfile() {
return profile;
}
public boolean login(String theUserId, String thePassword) {
return profile.authenticate(theUserId, thePassword);
}
public void setEMail(String newEMail) {
eMail = newEMail;
}
public void setName(String newName) {
name = newName;
}
public void setProfile(Profile newProfile) {
profile = newProfile;
}
}
public class Profile {
private String userId;
private String password;
public Profile(String theUserId, String thePassword) {
setUserId(theUserId);
setPassword(thePassword);
}
public boolean authenticate(String theUserId, String thePassword) {
return ((theUserId.equals(userId)) && (thePassword.equals(password)));
}
public String getPassword() {
return password;
}
public String getUserId() {
return userId;
}
Profile.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-14 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
public void setPassword(String newPassword) {
password = newPassword;
}
public void setUserId(String newUserId) {
userId = newUserId;
}
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-1
V3.1
EXempty
Exercise 5. Class Methods and Variables
What This Exercise Is About
In this exercise you will reuse the Customer and Profile classes that
you created in exercise 12. In addition you will create Cupboard and
Test classes. The Cupboard class is a static repository that contains a
collection of Customer references and a collection of Test instances.
The UML class diagrams shown below depict the classes that you will
create in this exercise.
Customer
-name : String
-eMail : String
-profile : Profile
+Customer(String,String) :
+Customer() :
+createProfile(String,String,String) : void
+getEMail() : String
+getName() : String
+getProfile() : Profile
+login(String, String) : boolean
+setEmail(String) : void
+setName(String) : void
+setProfile(Profile) : void
Driver
+main(String[]) : void
Cupboard
-customerCollection : Vector
-testCollection : Vector
+init() : void
+listTests(Customer) : void
+login(String,String) : Customer
Test
+DEVELOPMENT : String = "DEVELOPMENT"
+PRODUCTON : String = "PRODUCTON"
-nextTestdNumber : int = 1
-name : String
-area : String
-idNumber : int
-status : String
+Test()
+Test(String,String) :
+getArea() : String
+getdNumber() : int
+getName() : String
-getNextTestdNumber() : int
+getStatus() : String
+setArea(String) : void
+setdNumber(String) : void
+setName(String) : void
+setStaus(String) : void
ProfiIe
+DEVELOPER : String = "DEVELOPER"
+USER: String = "USER"
-password : String
-privilege : String
-userd : String
+Profile() :
+Profile(String,String) :
+authenticate(String,String) : boolean
+getPassword() : String
+getPrivilege() : String
+getUserd() : String
+setPassword(String) : void
+setPrivilege( String) : void
+setUserd(String) : void
0..n
0..n
1
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
What You Should Be Able to Do
At the end of the lab, you should be able to:
Use static methods and variables
Declare static variables
Write static methods
Learning Strategy
Individual exercise
Required Materials
Sun J2SE SDK 1.4.2
Windows Notepad or equivalent
Solutions to lab4 (Creating Classes exercise)
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-3
V3.1
EXempty Exercise Instructions
A Test instance represents a test that is either under development or in production. An
instance variable depicts the test status as being DEVELOPMENT or PRODUCTION.
The Cupboard class is a central repository of instances of Customer and Test. You will
use two java.util.Vector instances to hold the references. Cupboard is implemented using
static methods and static variables (fields). Thus, there is only one executable rendition of
Cupboard, making it behave much like a singleton instance. The init() method of Cupboard
will prime its repository vectors with instances Customer and Test.
How does a Customer instance log in under this new version of the application? The
Cupboard has a login method that accepts a user ID and password. Its implementation
delegates to the proper Customer login() method if an instance of that Customer exists in
its repository. The Customer.login() calls the authenticate method of its associated Profile
instance. If anything goes wrong, the Customer isn't logged in.
The Cupboard is able to list the Test instances available to the kind of a given logged in
Customer instance. Each Customer is a consumer of tests of a status that is permissible
for the given kind of Customer. How are kinds of Customer specified?
You shall set the privilege field of Profile class to an appropriate privilege level for the
associated Customer. There are two privileges: USER and DEVELOPER. A USER may
only access tests in PRODUCTION status. A DEVELOPER may only access tests in
DEVELOPMENT status.
You will implement a driver procedure in Driver.main() that will initialize the Cupboard
using its init method. Next you will log in a user ID and password to the Cupboard. The
privilege of the profile will be DEVELOPER. Then your driver will ask the Cupboard to list
the test names available to the kind of Customer that is logged into the system. Tests of
DEVELOPMENT status will display. Finally, you will log in a user ID that has USER status.
Tests of PRODUCTION status will display.
Directions
Step A: Create a Directory
1. Using a command prompt window, create a new lab5 directory beneath C:\OOPwJava.
This will contain the classes for this exercise.
Step B: Reuse Existing Classes
In this step, you will copy your existing classes to your new directory so that you can
continue building upon them.
1. Copy the Driver, Profile, and Customer classes from the previous exercise directory
(lab4) to your empty directory lab5.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Step C: Create a Test Class
In this step you will create a Test class. This Test class is used to represent a pool of
questions that can be selected for an exam.
1. Using the editor, define the public Test class within the lab5 directory. Let its superclass
default to java.lang.Object by not extending another class. Note: The detailed steps
have been omitted. If you need help, please see previous exercises for the step-by-step
instructions.
2. Add the fields (instance variables) to the Test class that are represented on the UML
diagram; code the public getter and setter for each field.
a. The first field is named area, it should be of type String and private. Getter and
setter should be public. A sample is:
private String area;
public String getArea() {
return area;
}
public void setArea(String newArea) {
area = newArea;
}
b. The second field is named name, it should be of type String and private. Getter
and setter should be public.
c. The third field is named idNumber, it should be of type int and private. Getter and
setter should be public.
3. Create a new constructor in the Test class that takes two parameters, the name of the
test, and the area of the test, and initializes the fields.
a. Write the source code for the new two argument constructor to initialize the name
and area fields, using their setters, to the parameters passed in.
Our solution looks like:
public Test(String theName, String theArea) {
setName(theName);
setArea(theArea);
}
4. Create a static field named NextTestIdNumber, of type int, initialize it to 1, make it
private, and do not code any getter and setter methods.
Our solution is:
private static int nextTestIdNumber = 1;
5. Create a static getNextTestIdNumber() method in the Test class. This method should
return the current value of NextTestIdNumber, and then increment the value of
nextTestIdNumber using the postfix incrementor ++.
Our solution for this method looks like:
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-5
V3.1
EXempty
private static int getNextTestIdNumber() {
return nextTestIdNumber++;
}
6. Modify Test's two-argument constructor so that it sets the idNumber field to be the next
test ID number.
a. Scroll to the Test(String, String) constructor. After the current initialization code,
use the setter method for idNumber to set the value to the result returned from
getNextTestIdNumber() message.
Our solution for the constructor now looks like this:
public Test(String theName, String theArea) {
setName(theName);
setArea(theArea);
setIdNumber(getNextTestIdNumber());
}
7. Save the file as C:\OOPwJava\lab5\Test.java.
8. Modify the Driver's main(String[ ]) method to create several tests and print their
information to the Console window.
a. Use the editor to open the Driver.java file in directory lab5. Scroll to the
main(String[ ]).
b. After the lines of code to create Customers and Profiles, create several test
instances and assign references as follows: (call the first one "test1", the second
"test2", and so forth). Remember to type the variable to be Test.
c. Using System.out.println(), print the test name, area, and test number to the console
window.
d. Our solution (for two tests) looks like this:
Test test1 = new Test("Basic Java2 Syntax", "Application
Development");
System.out.println(
"The first test's name is: "
+ test1.getName()
+ ", and its area is: "
+ test1.getArea()
+ ", and its test id number is: "
+ test1.getIdNumber());
Test test2 = new Test("Java Servlets", "Application
Development");
System.out.println(
"The second test's name is: "
+ test2.getName()
+ ", and its area is: "
+ test2.getArea()
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-6 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
+ ", and its test id number is: "
+ test2.getIdNumber());
9. Save the Driver.java file.
10. Compile Driver.java in the command prompt window. This should also cause the
compilation of Customer, Profile, and Test. The compile should look something like:
C:\OOPwJava\lab5> javac Driver
Fix any errors before proceeding.
11. Execute Driver. (java Driver in the command prompt window). The following
should display in the window:
Adam logged in successfully
Charlene did not log in successfully
The first test's name is: Basic Java2 Syntax, and it's area is:
Application Development, and it's test id number is: 1
The second test's name is: Java Servlets, and it's area is:
Application Development, and it's test id number is: 2
(Note: That each test has a different idNumber).
Step D: Create the Cupboard Class
In this step you will create a class that will hold instances of Test and Customer. In a real
application you need some way to control access to the available tests, and to the
customers. In our application, the Cupboard class is the one that will do this for us.
1. Using the editor, define the Cupboard class within the lab5 directory. Let its superclass
default to java.lang.Object.
2. Within the class definition, define a private static testCollection field of type
java.util.Vector; do not code any getter and setter methods. Initialize the field to be
new java.util.Vector().
3. Also define a private static customerCollection field of type java.util.Vector, do not
code getter and setter methods. Initialize the field to be new java.util.Vector().
4. Define a public static void init() method in the Cupboard class that will create some
instances of Test and add them to the testCollection, and some instances of Customer
and add them to the customerCollection.
a. The code for this method can be copied directly from the Driver main(String[])
method. You will just need to remove the System.out.println() statements.
Our solution for this method looks like:
public static void init() {
Customer theCustomer =
new Customer("Adam", "adam@hotmail.com");
Profile theProfile = new Profile("ADAM", "ADAM123");
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-7
V3.1
EXempty
theCustomer.setProfile(theProfile);
Customer anotherCustomer =
new Customer("Charlene", "char@email.com");
Profile anotherProfile = new Profile("CHAR", "CHAR321");
anotherCustomer.setProfile(anotherProfile);
customerCollection.add(theCustomer);
customerCollection.add(anotherCustomer);
Test test1 =
new Test("Basic Java2 Syntax", "Application
Development");
Test test2 =
new Test("Java Servlets", "Application Development");
testCollection.add(test1);
testCollection.add(test2);
}
5. Add another method, public static Customer login(String, String) method, to the
Cupboard class that will search through the customerCollection and find the one
whose profile's userId matches the provided userId and logs them in. If the customer
logs in successfully, return the customer, otherwise return null.
a. Iterate through the objects stored in the customerCollection using a for loop.
b. Remember to cast the retrieved elements from customerCollection to be of type
Customer.
c. If the customer's profile's userId is equal to the userId passed in then attempt to log
the user in.
d. If the user logs in successfully then return the customer.
e. If the user does not log in successfully, or the customer is not found in the collection,
then return null.
Here is our solution for this method:
public static Customer login(String theUserId, String
thePassword) {
Customer theCustomer = null;
for (int index = 0; index < customerCollection.size();
index++) {
theCustomer = (Customer)
customerCollection.get(index);
if
(theCustomer.getProfile().getUserId().equals(theUserId))
break;
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-8 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
}
if (theCustomer != null) {
boolean loggedIn = theCustomer.login(theUserId,
thePassword);
if (loggedIn) {
return theCustomer;
}
}
return null;
}
6. Save the file as C:\OOPwJava\lab5\Cupboard.java.
7. Modify the Driver main(String[ ]) method to init() the Cupboard, and then attempt to
log the two customers in. If the customer logs in successfully, print a welcome message,
if not print an access denied message.
a. Remove all the existing code from the main(String[ ]) method. (This was all
initialization code that has been moved to the init() method on Cupboard.)
b. Initialize the Cupboard by sending the init() message to the class.
c. Use the login(String, String) method of Cupboard to attempt to log in two
customers (have one be successful, and one not). Remember the login(String,
String) method of Cupboard will return a reference to an instance of Customer if
the login is successful, otherwise it will return null.
Our solution for the main(String[ ]) method looks like this:
public static void main(java.lang.String[] args) {
Cupboard.init();
Customer someCustomer = Cupboard.login("ADAM", "ADAM123");
if (someCustomer != null)
System.out.println(
"Welcome "
+ someCustomer.getName()
+ " you logged in successfully");
else
System.out.println("Sorry, access denied");
someCustomer = Cupboard.login("CHAR", "WRONGPASSWORD");
if (someCustomer != null)
System.out.println(
"Welcome "
+ someCustomer.getName()
+ " you logged in successfully");
else
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-9
V3.1
EXempty
System.out.println("Sorry, access denied");
}
8. Save the Driver.java file.
9. Compile Driver.java in the command prompt window. This should also cause the
compilation of Cupboard. Fix any errors before proceeding.
10. Execute Driver. The following should display in the window:
Welcome Adam you logged in successfully
Sorry, access denied
Step E: Create Constants to Define Tests and Customers
In this step, you will define several constants (using static variables). You need to be able to
differentiate development and production tests, as well as user and developer customers.
1. Add a field to the Test class called status. It should be private, of type String and have
public getter and setter methods.
2. Add a field to the Profile class called privilege. It should be private, of type String and
have public getter and setter methods.
Information: It would be easy enough just to leave this here and not define the
constants. But, you would end up with hard coded values all over in your application
trying to determine if a test is in development or in production. You will use final static
variables to define these constants and then access the variables instead of hard
coding the values.The final modifier denotes a constant in Java.
3. Add a field to the Test class called DEVELOPMENT (yes, in all upper case letters). It
should be public, final, static, of type String and be initialized to the value
"DEVELOPMENT" (yes, include the quotation marks, it is a String). Do not create
getter and setter methods for this field.
4. Add a field to the Test class called PRODUCTION. It should be public, final, static, of
type String and be initialized to the value "PRODUCTION". Do not create getter and
setter methods for this field.
5. Modify the Cupboard's init() method to set the status of the tests that are created. Set
one to be PRODUCTION, and the other to be DEVELOPMENT.
a. Use the setStatus(String) method of Test to set the status of each test that is
created. Use Test.PRODUCTION, and Test.DEVELOPMENT for the parameters.
Here is our solution within the init() method of Cupboard:
Test test1 = new Test("Basic Java2 Syntax", "Application
Development");
test1.setStatus(Test.DEVELOPMENT);
Test test2 = new Test("Java Servlets", "Application
Development");
test2.setStatus(Test.PRODUCTION);
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-10 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
6. Add a field to the Profile class called USER. It should be public, final, static, of type
String and be initialized to the value "USER". Do not create getter and setter methods
for this field.
7. Add a field to the Profile class called DEVELOPER. It should be public, final, static, of
type String and be initialized to the value "DEVELOPER". Do not create getter and
setter methods for this field.
Information: You could go and modify the init() method of Cupboard to set the
privilege of a profile to Profile.USER or Profile.DEVELOPER. However, you will solve
this problem a little differently. You will encapsulate the fact that the Customer class
uses an instance of Profile. You will have the customer create the profile, rather than
creating the profile externally to customer and then setting it.
8. Add a method createProfile(String, String, String) to the Customer class that takes a
userId, password, and privilege as a parameter. The method should be public, and
have a return type of void. It should create a new instance of Profile and associate it
with the customer.
a. Use the two-argument constructor already defined in Profile, passing the userId and
password as parameters.
b. Using the setPrivilege(String) method of Profile, passing the privilege as a
parameter.
Our solution looks like this:
public void createProfile(String theUserId, String
thePassword, String thePrivilege) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(thePrivilege);
setProfile(theProfile);
}
9. Modify the Cupboard's init() method to use the createProfile(String, String, String)
method of Customer, instead of using the setProfile(Profile) method. Have one of the
customers be a USER and one be a DEVELOPER.
Here is our whole solution for the init() method on Cupboard:
public static void init() {
Customer theCustomer = new Customer("Adam",
"adam@hotmail.com");
theCustomer.createProfile("ADAM", "ADAM123",
Profile.USER);
Customer anotherCustomer = new Customer("Charlene",
"char@email.com");
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-11
V3.1
EXempty
anotherCustomer.createProfile("CHAR", "CHAR321",
Profile.DEVELOPER);
customerCollection.add(theCustomer);
customerCollection.add(anotherCustomer);
Test test1 = new Test("Basic Java2 Syntax", "Application
Development");
test1.setStatus(Test.DEVELOPMENT);
Test test2 = new Test("Java Servlets", "Application
Development");
test2.setStatus(Test.PRODUCTION);
testCollection.add(test1);
testCollection.add(test2);
}
10. Open Driver's main(String[ ]) method and change Charlene's login to pass her correct
password "CHAR321".
11. Save all the editor sessions for the files you have modified: Test.java, Profile.java,
Cupboard.java, Customer.java, and Driver.java.
12. Compile Driver.java in the command prompt window. This should also cause the
compilation of Test, Profile, Cupboard, and Customer. Fix any errors before
proceeding.
13. Execute Driver. The following should display in the window:
Welcome Adam you logged in successfully
Welcome Charlene you logged in successfully
Step F: Use the Constants to List Tests for a Customer
In this step you will put the constants defined to good use. You will add the ability to list
tests for a customer. A developer should be able to see tests that are in development, and
users should be able to see only tests that are in production.
1. Create a public static void listTests(Customer) method in the Cupboard class that
will search through the testCollection and find the tests that the customer should be
able to see (based on their profile's privilege value). Print the tests that the customer
can see to the Console.
a. Loop through the elements in the testCollection using a for loop.
b. If the test's status is Test.DEVELOPMENT and the customer's profile's privilege is
Profile.DEVELOPER, or the test's status is Test.PRODUCTION and the customer's
profile's privilege is Profile.USER then print the test out to the console using
System.out.println().
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-12 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Our solution looks like this:
public static void listTests(Customer theCustomer) {
String filter = "";
if
(theCustomer.getProfile().getPrivilege().equals(Profile.DEVEL
OPER))
filter = Test.DEVELOPMENT;
else
if
(theCustomer.getProfile().getPrivilege().equals(Profile.USER)
)
filter = Test.PRODUCTION;
for (int index = 0; index < testCollection.size();
index++) {
Test theTest = (Test) testCollection.get(index);
if (theTest.getStatus().equals(filter))
System.out.println(
"\t"
+ theTest.getIdNumber()
+ " : "
+ theTest.getName()
+ " : "
+ theTest.getArea());
}
}
2. Modify Driver's main(String[ ]) method to call Cupboard's listTests(Customer)
method with the non-null return of the login(String, String) after printing out the
welcome. (Remember to do this for after both logins.)
a. Our (partial) solution looks like this:
...
if (someCustomer != null) {
System.out.println(
"Welcome " + someCustomer.getName() + " you logged
in successfully");
Cupboard.listTests(someCustomer);
} else
System.out.println("Sorry, access denied");
...
3. You may wish to add some more tests to the init() method in Cupboard so that it lists
more than one test for each customer. (Our solution has added several more.)
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-13
V3.1
EXempty
4. Save all the editor sessions for the files you have modified: Cupboard.java, and
Driver.java.
5. Compile Driver.java in the command prompt window. This should also cause the
compilation of Cupboard. Fix any errors before proceeding.
6. Execute Driver. The following should display in the window:
Welcome Adam you logged in successfully
2 : Java Servlets : Application Development
3 : Java Applets : Application Development
5 : XML Parsers : XML
6 : Beginning HTML : Web Development
Welcome Charlene you logged in successfully
1 : Basic Java2 Syntax : Application Development
4 : XML Tags : XML
Summary
You implemented the Cupboard class composed entirely of static variables and methods.
These are often called class variables or class methods because they are associated with
the class. They do not need an instance to be accessed, but if you did instantiate
Cupboard, you could access them from the reference also.
You used the static int nextIdNumber field in the Test class to control the assignment of
unique ID numbers to tests. This is a common solution used where a class must control a
value given to its instances.
You also accessed core static methods in your use of the java.lang.Character class to
implement password validation rules.
END OF LAB
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-14 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Reference code
Below are the classes for this exercise.
public class Cupboard {
private static java.util.Vector testCollection = new java.util.Vector();
private static java.util.Vector customerCollection = new
java.util.Vector();
public static void init() {
Customer theCustomer = new Customer("Adam", "adam@hotmail.com");
theCustomer.createProfile("ADAM", "ADAM123", Profile.USER);
Customer anotherCustomer = new Customer("Charlene", "char@email.com");
anotherCustomer.createProfile("CHAR", "CHAR321", Profile.DEVELOPER);
customerCollection.add(theCustomer);
customerCollection.add(anotherCustomer);
Test test1 = new Test("Basic Java2 Syntax", "Application Development");
test1.setStatus(Test.DEVELOPMENT);
Test test2 = new Test("Java Servlets", "Application Development");
test2.setStatus(Test.PRODUCTION);
Test test3 = new Test("Java Applets", "Application Development");
test3.setStatus(Test.PRODUCTION);
Test test4 = new Test("XML Tags", "XML");
test4.setStatus(Test.DEVELOPMENT);
Test test5 = new Test("XML Parsers", "XML");
test5.setStatus(Test.PRODUCTION);
Test test6 = new Test("Beginning HTML", "Web Development");
test6.setStatus(Test.PRODUCTION);
testCollection.add(test1);
testCollection.add(test2);
testCollection.add(test3);
testCollection.add(test4);
testCollection.add(test5);
Cupboard.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-15
V3.1
EXempty
testCollection.add(test6);
}
public static void listTests(Customer theCustomer) {
String filter = "";
if (theCustomer.getProfile().getPrivilege().equals(Profile.DEVELOPER))
filter = Test.DEVELOPMENT;
else
if (theCustomer.getProfile().getPrivilege().equals(Profile.USER))
filter = Test.PRODUCTION;
for (int index = 0; index < testCollection.size(); index++) {
Test theTest = (Test) testCollection.get(index);
if (theTest.getStatus().equals(filter))
System.out.println(
"\t"
+ theTest.getIdNumber()
+ " : "
+ theTest.getName()
+ " : "
+ theTest.getArea());
}
}
public static Customer login(String theUserId, String thePassword) {
Customer theCustomer = null;
for (int index = 0; index < customerCollection.size(); index++) {
theCustomer = (Customer) customerCollection.get(index);
if (theCustomer.getProfile().getUserId().equals(theUserId))
break;
}
if (theCustomer != null) {
boolean loggedIn = theCustomer.login(theUserId, thePassword);
if (loggedIn) {
return theCustomer;
}
}
return null;
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-16 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
}
}
public class Customer {
private String name;
private String eMail;
private Profile profile;
public Customer(String theName, String theEMail) {
setName(theName);
setEMail(theEMail);
}
public void createProfile(String theUserId, String thePassword, String
thePrivilege){
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(thePrivilege);
setProfile(theProfile);
}
public String getEMail() {
return eMail;
}
public String getName() {
return name;
}
public Profile getProfile() {
return profile;
}
public boolean login(String theUserId, String thePassword) {
return profile.authenticate(theUserId, thePassword);
}
public void setEMail(String newEMail) {
eMail = newEMail;
}
public void setName(String newName) {
name = newName;
}
public void setProfile(Profile newProfile) {
profile = newProfile;
}
Customer.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-17
V3.1
EXempty
}
public class Driver {
public static void main(String[] args) {
Cupboard.init();
Customer someCustomer = Cupboard.login("ADAM", "ADAM123");
if (someCustomer != null) {
System.out.println(
"Welcome " + someCustomer.getName() + " you logged in
successfully");
Cupboard.listTests(someCustomer);
} else
System.out.println("Sorry, access denied");
someCustomer = Cupboard.login("CHAR", "CHAR321");
if (someCustomer != null) {
System.out.println(
"Welcome " + someCustomer.getName() + " you logged in
successfully");
Cupboard.listTests(someCustomer);
} else
System.out.println("Sorry, access denied");
}
}
public class Profile {
private String userId;
private String password;
private String privilege;
public final static String USER = "USER";
public final static String DEVELOPER = "DEVELOPER";
public Profile() {
super();
}
public Profile(String theUserId, String thePassword) {
setUserId(theUserId);
setPassword(thePassword);
Driver.java
Profile.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-18 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
}
public boolean authenticate(String theUserId, String thePassword) {
return ((theUserId.equals(userId)) && (thePassword.equals(password)));
}
public java.lang.String getPassword() {
return password;
}
public java.lang.String getPrivilege() {
return privilege;
}
public String getUserId() {
return userId;
}
public void setPassword(String newPassword) {
password = newPassword;
}
public void setPrivilege(String newPrivilege) {
privilege = newPrivilege;
}
public void setUserId(String newUserId) {
userId = newUserId;
}
}
public class Test {
private String name;
private String area;
private int idNumber;
private static int NextTestIdNumber = 1;
public final static String DEVELOPMENT = "DEVELOPMENT";
public final static String PRODUCTION = "PRODUCTION";
private java.lang.String status;
public Test(String theName, String theArea) {
setName(theName);
setArea(theArea);
setIdNumber(getNextTestIdNumber());
}
public String getArea() {
return area;
Test.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-19
V3.1
EXempty
}
public int getIdNumber() {
return idNumber;
}
public String getName() {
return name;
}
private static int getNextTestIdNumber() {
return NextTestIdNumber++;
}
public String getStatus() {
return status;
}
public void setArea(String newArea) {
area = newArea;
}
public void setIdNumber(int newIdNumber) {
idNumber = newIdNumber;
}
public void setName(String newName) {
name = newName;
}
public void setStatus(String newStatus) {
status = newStatus;
}
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-20 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 6. Object Hierarchy 6-1
V3.1
EXempty
Exercise 6. Object Hierarchy
What This Exercise Is About
This exercise is about using and adding to the hierarchy of classes.
The UML class diagrams below depict the class structure of the
application.
3HUVRQ {abstract}
-name : String
-eMail : String
-profile : Profile
+Person()
+Person(String,String)
+createProfile(String,String) : void
+getEmail() : String
+getName() : String
+getProfile() : Profile
+login(String, String) : boolean
+setEmail(String) : void
+setName(String) : void
+setProfile(Profile) : void
ProfiIe
+DEVELOPER : String = "DEVELOPER"
+USER : String = "USER"
-password : String
-privilege : String
-userd : String
+Profile()
+Profile(String,String)
+authenticate(String,String) : boolean
+getPassword() : String
+getPrivilege() : String
+getUserd() : String
+setPassword(String) : void
+setPrivilege(String) : void
+setUserd(String) : void
Driver
+main(String[]) : void
Cupboard
-personCollection : Vector
-testCollection : Vector
+init() : void
+listTests(Person) : void
+login(String,String) : Person
Test
+DEVELOPMENT : String = "DEVELOPMENT"
+PRODUCTON : String = "PRODUCTON"
-nextdNumber : int = 1
-name : String
-area : String
-idNumber : int
-status : String
+Test()
+Test(String,String)
+getArea() : String
+getdNumber() : int
+getName : String
-getNextTestdNumber() : int
+getStatus() : String
+setArea(String) : void
+setdNumber(int) : void
+setName(String) : void
+setStatus(String) : void
Customer
+Customer(String,String)
+Customer()
+createProfile(String,String) : void
DeveIoper
+Developer(String,String)
+Developer()
+createProfile(String,String) : void
1
0..n
0..n
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
6-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
What You Should Be Able to Do
At the end of the lab, you should be able to:
Create subclasses
Override methods
Use super()
Required Materials
Sun J2SE SDK 1.4.2
Windows Notepad or equivalent
Solutions to lab5 (Static Methods and Variables exercise)
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 6. Object Hierarchy 6-3
V3.1
EXempty Exercise Instructions
You will decompose the Customer class of the prior exercise into a small class hierarchy.
The Customer class will become an abstract base class called Person. It will declare an
abstract createProfile(userId, password) method. You will create a Customer subclass and
a Developer subclass of Person. Each will implement the createProfile() method by
creating a profile unique to the kind of subclass. Each kind of Person knows its assigned
exam system privilege level. It will set that privilege into its profile in its override of the
createProfile() method.
Directions
Step A: Create a Directory
1. Using a command prompt window, create a new lab6 directory beneath C:\OOPwJava.
This will contain the classes for this exercise.
Step B: Reuse Existing Classes
1. Copy the Cupboard, Customer, Driver, Profile, and Test classes from the previous
exercise directory (lab5) to your empty directory lab6.
Step C: Create an Abstract Class
In this step you will create an abstract class called Person. Most of the required behavior
for the Person class already exists in the Customer class. Rather than creating the Person
class and copying everything, you will just copy the Customer.java file (class) to a new
Person.java file. In a following step you will restructure the Customer class.
1. Use a command prompt window or Windows Explorer to make a copy of
Customer.java named Person.java in directory lab6.
2. Edit the Person.java file, adding the keyword abstract before the class keyword, and
changing the class name to Person.
3. Change the signature of the two argument constructor from Customer to Person.
You're creating Persons, not Customers, at this level in the hierarchy.
4. Modify the createProfile(String, String, String) method of Person. Remove the third
parameter, add the keyword abstract before the return type, and substitute a semicolon
(end of statement) for the body (curly braces, and everything within them).
The method should look like this:
public abstract void createProfile(String theUserId, String
thePassword);
5. Save the file.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
6-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Step D: Extend the Person Class with Customer and Developer Classes
1. Restructure the Customer class to extend Person.
a. Edit the Customer.java file. Change the class signature to indicate that Customer
now subclasses Person by adding extends Person.
b. Remove all the instance variable declarations, since they now are defined in Person.
Also remove the getters and setters.
c. Since all the login information is kept at the Person level, you can use the methods
defined at that level. Remove the login(String, String) method declaration in
Customer.
d. Change the two argument constructor to invoke Person's two-argument constructor:
public Customer(String theName, String theEMail) {
super(theName, theEMail);
}
e. Remove the third parameter of the createProfile() method.
f. Code the implementation for Customer's createProfile(String, String) by creating
a new instance of Profile using the theUserId and thePassword parameters. Be
sure to use the static constant Profile.USER for the privilege. Then set the profile for
the customer to be this new instance of Profile. This distinguishes a Customer from
other kinds of Person.
Our solution looks like:
public void createProfile(String theUserId, String
thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.USER);
setProfile(theProfile);
}
2. Save the Customer.java file.
3. Since the only difference between Customer and Developer is the implementation of
the createProfile method, you can start the definition of Developer by copying the
Customer.java file to a new file Developer.java in the lab6 directory.
4. Edit Developer.java, and change the class declaration from Customer to Developer.
5. Change the two-argument constructor signature to be for the Developer class.
6. Change the implementation for Developer's createProfile(String, String). Use the
same format as used for Customer's, but use the static constant Profile.DEVELOPER
for the privilege value.
7. Save the Developer.java file.
Step E: Modify Class Cupboard
In this step you will modify the Cupboard class so that it can use (and store) Persons
rather than just Customers. You will then modify the init() method to load Person
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 6. Object Hierarchy 6-5
V3.1
EXempty
references that have DEVELOPER or USER privilege according to whether the person is
an instance of Customer or Developer.
1. Rename Cupboard.customerCollection to personCollection to indicate that the
collection is generic.
a. Edit Cupboard.java and scroll to the field declarations.
b. Replace the name customerCollection with personCollection.
2. Modify the Cupboard.init() method. Change the type of the two Customer variables to
be of type Person. Change theCustomer and anotherCustomer to thePerson and
anotherPerson to alleviate any confusion as to what type of objects they are
referencing. Create one Customer and one Developer. Change the name of the
customerCollection to personCollection.
a. In the creation of the theCustomer change the type of the variable to Person and
rename it to thePerson.
b. In the call of createProfile(), remove the third parameter.
Information: Now that you have created Customer as a subclass of Person, and
defined the createProfile(String, String) in Customer to use Profile.USER, you no
longer need to pass it from this creation statement.
c. In the creation of the anotherCustomer change the type of the variable to Person,
rename it to anotherPerson and change the class that you are creating an instance
of to Developer.
d. In the call to createProfile(), remove the third parameter. (Note: Since this is an
instance of Developer the createProfile(String, String) method in the Developer
class uses Profile.DEVELOPER.)
e. Change the variable customerCollection to personCollection in the statements
where thePerson and anotherPerson are added to the Vector.
Here's our solution for the first several lines of the init() method:
...
Person thePerson = new Customer("Adam", "adam@hotmail.com");
thePerson.createProfile("ADAM", "ADAM123");
Person anotherPerson = new Developer("Charlene",
"char@email.com");
anotherPerson.createProfile("CHAR", "CHAR321");
personCollection.add(thePerson);
personCollection.add(anotherPerson);
...
3. Modify Cupboard's login(String, String) method so that it has a return type of
Person. Change all references to the Customer class to Person. Return a matching
Person reference from the personCollection.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
6-6 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Here is our solution for this method:
public static Person login(String theUserId, String thePassword)
{
Person thePerson = null;
for (int index = 0; index < personCollection.size(); index++)
{
thePerson = (Person) personCollection.get(index);
if (thePerson.getProfile().getUserId().equals(theUserId))
break;
}
if (thePerson != null) {
boolean loggedIn = thePerson.login(theUserId,
thePassword);
if (loggedIn) {
return thePerson;
}
}
return null;
}
4. Modify Cupboard's listTests(Customer) method so that it takes a parameter of type
Person. (If you like, you can change the variable name from theCustomer to
thePerson, but this is unnecessary as it is only the type of the variable that is
important).
5. Save the Cupboard.java file.
Step F: Modify Driver Main(string[ ]) and Test the Program
1. Edit Driver.java. Scroll to the main(String[ ] args) method. Change the type of the
someCustomer variable from Customer to Person. (Again, you can change the name
of the variable, but this is unnecessary).
2. Save the Driver.java file.
3. Compile Driver.java in the command prompt window. This should also cause the
compilation of Person, Customer, Developer and Cupboard. Fix any errors before
proceeding.
4. Execute Driver. The following should display in the window:
Welcome Adam you logged in successfully
2 : Java Servlets : Application Development
3 : Java Applets : Application Development
5 : XML Parsers : XML
6 : Beginning HTML : Web Development
Welcome Charlene you logged in successfully
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 6. Object Hierarchy 6-7
V3.1
EXempty
1 : Basic Java2 Syntax : Application Development
4 : XML Tags : XML
Summary
This program exhibits the behavior of the version of the application that you completed in
the prior exercise. In that exercise you had a collection of Customer references, each
having one of two profile privileges.
In this exercise you created a collection of Person references. Each reference has a
concrete type of either Customer or Developer. The constructors of Customer and
Developer each use super(...) to pass arguments to the Person constructor.
Each Person reference has a profile privilege unique to its concrete type. Each of the
subclasses of Person will override the createProfile() method and set its privilege by calling
the setProfile() method implemented in the base class Person.
The driver passes this Person to Cupboard.listTests(Person). Here, the test collection is
filtered and displayed according to the Person's profile privilege, as in the prior exercise.
END OF LAB
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
6-8 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Reference Code
public class Cupboard {
private static java.util.Vector testCollection = new java.util.Vector();
private static java.util.Vector personCollection = new
java.util.Vector();
public static void init() {
Person thePerson = new Customer("Adam", "adam@hotmail.com");
thePerson.createProfile("ADAM", "ADAM123");
Person anotherPerson = new Developer("Charlene", "char@email.com");
anotherPerson.createProfile("CHAR", "CHAR321");
personCollection.add(thePerson);
personCollection.add(anotherPerson);
Test test1 = new Test("Basic Java2 Syntax", "Application Development");
test1.setStatus(Test.DEVELOPMENT);
Test test2 = new Test("Java Servlets", "Application Development");
test2.setStatus(Test.PRODUCTION);
Test test3 = new Test("Java Applets", "Application Development");
test3.setStatus(Test.PRODUCTION);
Test test4 = new Test("XML Tags", "XML");
test4.setStatus(Test.DEVELOPMENT);
Test test5 = new Test("XML Parsers", "XML");
test5.setStatus(Test.PRODUCTION);
Test test6 = new Test("Beginning HTML", "Web Development");
test6.setStatus(Test.PRODUCTION);
testCollection.add(test1);
testCollection.add(test2);
testCollection.add(test3);
testCollection.add(test4);
testCollection.add(test5);
testCollection.add(test6);
Cupboard.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 6. Object Hierarchy 6-9
V3.1
EXempty
}
public static void listTests(Person thePerson) {
String filter = "";
if (thePerson.getProfile().getPrivilege().equals(Profile.DEVELOPER))
filter = Test.DEVELOPMENT;
else
if (thePerson.getProfile().getPrivilege().equals(Profile.USER))
filter = Test.PRODUCTION;
for (int index = 0; index < testCollection.size(); index++) {
Test theTest = (Test) testCollection.get(index);
if (theTest.getStatus().equals(filter))
System.out.println(
"\t"
+ theTest.getIdNumber()
+ " : "
+ theTest.getName()
+ " : "
+ theTest.getArea());
}
}
public static Person login(String theUserId, String thePassword) {
Person thePerson = null;
for (int index = 0; index < personCollection.size(); index++) {
thePerson = (Person) personCollection.get(index);
if (thePerson.getProfile().getUserId().equals(theUserId))
break;
}
if (thePerson != null) {
boolean loggedIn = thePerson.login(theUserId, thePassword);
if (loggedIn) {
return thePerson;
}
}
return null;
}
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
6-10 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
public class Customer extends Person {
public Customer(String theName, String theEMail) {
super(theName, theEMail);
}
public void createProfile(String theUserId, String thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.USER);
setProfile(theProfile);
}
}
public class Developer extends Person {
public Developer(String theName, String theEMail) {
super(theName, theEMail);
}
public void createProfile(String theUserId, String thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.DEVELOPER);
setProfile(theProfile);
}
}
public class Driver {
public static void main(String[] args) {
Cupboard.init();
Person somePerson = Cupboard.login("ADAM", "ADAM123");
if (somePerson != null) {
System.out.println(
"Welcome " + somePerson.getName() + " you logged in
successfully");
Cupboard.listTests(somePerson);
} else
Customer.java
Developer.java
Driver.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 6. Object Hierarchy 6-11
V3.1
EXempty
System.out.println("Sorry, access denied");
somePerson = Cupboard.login("CHAR", "CHAR321");
if (somePerson != null) {
System.out.println(
"Welcome " + somePerson.getName() + " you logged in
successfully");
Cupboard.listTests(somePerson);
} else
System.out.println("Sorry, access denied");
}
}
public abstract class Person {
private String name;
private String eMail;
private Profile profile;
public Person(String theName, String theEMail) {
setName(theName);
setEMail(theEMail);
}
public abstract void createProfile(String theUserId, String thePassword);
public String getEMail() {
return eMail;
}
public String getName() {
return name;
}
public Profile getProfile() {
return profile;
}
public boolean login(String theUserId, String thePassword) {
return profile.authenticate(theUserId, thePassword);
}
public void setEMail(String newEMail) {
eMail = newEMail;
}
public void setName(String newName) {
name = newName;
}
public void setProfile(Profile newProfile) {
Person.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
6-12 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
profile = newProfile;
}
}
public class Profile {
private String userId;
private String password;
private String privilege;
public final static String USER = "USER";
public final static String DEVELOPER = "DEVELOPER";
public Profile(String theUserId, String thePassword) {
setUserId(theUserId);
setPassword(thePassword);
}
public boolean authenticate(String theUserId, String thePassword) {
return ((theUserId.equals(userId)) && (thePassword.equals(password)));
}
public String getPassword() {
return password;
}
public String getPrivilege() {
return privilege;
}
public String getUserId() {
return userId;
public void setPassword(String newPassword) {
password = newPassword;
}
public void setPrivilege(String newPrivilege) {
privilege = newPrivilege;
}
public void setUserId(String newUserId) {
userId = newUserId;
}
}
public class Test {
private String name;
Profile.java
Test.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 6. Object Hierarchy 6-13
V3.1
EXempty
private String area;
private int idNumber;
private static int NextTestIdNumber = 1;
public final static String DEVELOPMENT = "DEVELOPMENT";
public final static String PRODUCTION = "PRODUCTION";
private String status;
public Test(String theName, String theArea) {
setName(theName);
setArea(theArea);
setIdNumber(getNextTestIdNumber());
}
public String getArea() {
return area;
}
public int getIdNumber() {
return idNumber;
}
public String getName() {
return name;
}
private static int getNextTestIdNumber() {
return NextTestIdNumber++;
}
public String getStatus() {
return status;
}
public void setArea(String newArea) {
area = newArea;
}
public void setIdNumber(int newIdNumber) {
idNumber = newIdNumber;
}
public void setName(String newName) {
name = newName;
}
public void setStatus(String newStatus) {
status = newStatus;
}
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
6-14 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-1
V3.1
EXempty
Exercise 7. Packages
What This Exercise Is About
In this exercise you will reuse the classes you created in the prior
exercise, but you will place those classes into packages and use
access modifiers to control visibility. You will also create a new kind of
Person: a Reviewer class that will reside in its own package. The UML
class diagrams shown below depict the classes you will use in the
exercise.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
3HUVRQ
-name : String
-eMail : String
-profile : Profile
+Person()
+Person(String,String)
+createProfile(String,String) : void
+getEmail() : String
+getName() : String
+getProfile() : String
+login(String, String) : boolean
+setEmail(String) : void
+setName(String) : void
+setProfile(Profile) : void
ProfiIe
+DEVELOPER : String = "DEVELOPER"
+REVEWER : String = "REVEWER"
+USER : String = "USER"
-password : String
-privilege : String
-userd : String
+Profile(String,String)
+Profile()
~authenticate(String,String) : boolean
+getPassword() : String
+getPrivilege() : String
+getUserd() : String
+setPassword(String) : void
+setPrivilege(String) : void
+setUserd(String) : void
Driver
+main(String[]) : void
Cupboard
-personCollection : Vector
-testCollection : Vector
+init() : void
+listTests(Person) : void
+login(String,String) : Person
Test
+DEVELOPMENT : String = "DEVELOPMENT"
+PRODUCTON : String = "PRODUCTON"
-nextdNumber : int = 1
-name : String
-area : String
-idNumber : int
-status : String
+Test()
+Test(String,String)
+getArea() : String
+getdNumber() : int
+getName : String
-getNextTestdNumber() : int
+getStatus() : String
+setArea(String) : void
+setdNumber(int) : void
+setName(String) : void
+setStatus(String) : void
Customer
+Customer(String,String)
+Customer()
+createProfile(String,String) : void
DeveIoper
+Developer(String,String)
+Developer()
+createProfile(String,String) : void
Reviewer
+Reviewer()
+Reviewer(String,String)
+createProfile(String,String) : void
1
0..n
0..n
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-3
V3.1
EXempty What You Should Be Able to Do
At the end of the lab, you should be able to:
Create subclasses
Use the instance of keyword
Override methods
Use super() and super
Required Materials
Sun J2SE SDK 1.4.2
Windows Notepad or equivalent
Solutions to lab6 (Object Hierarchy exercise)
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Exercise Instructions
Prior to this exercise you've been placing your classes in a single package without really
thinking about what packages are. Packages help you avoid name collisions, promote
encapsulation through access modifiers, and are a delivery vehicle for functionally related
classes.
In this exercise you will place your Driver class into a separate package named driver. You
will continue to use the application model packages you created in the prior exercise, but
will move them into a model package. You will create a new class called Reviewer that
extends Person. It will reside in the model.reviewer package. You will apply appropriate
access modifiers to enable only the visibility required between classes, to promote
encapsulation.
Directions
Step A: Create Packages
1. Under a command prompt window, create a new model directory beneath
C:\OOPwJava\lab7. This directory will contain the Cupboard, Customer, Developer,
Person, Profile, and Test classes. This will now be known as the model package.
2. Under a command prompt window, create a new reviewer directory beneath
C:\OOPwJava\lab7\model. This will contain a Reviewer class. This will now be known
as the model.reviewer package.
3. Under a command prompt window, create a new driver directory beneath
C:\OOPwJava\lab7. This directory will contain the Driver class. This will now be known
as the driver package.
Step B: Reuse Existing Classes
1. Copy the Cupboard, Customer, Developer, Person, Profile, and Test classes from
the previous exercise package to your empty package model. These classes form the
application model. (Refer to previous exercises if you need step-by-step directions for
this procedure.)
2. Copy the Driver class to your new driver package.
3. The main(String[ ]) method needs to be updated. Currently, it is trying to reference
Cupboard and Person, but they are defined in package model. Fix this by importing
the package model into the Driver class.
a. In the class definition make the first line say: import lab7.model.*;
b. Save your changes and the errors will be resolved.
4. Add the correct package statement to each class. The package name is the name of the
directory, the class is located. This has to be the first statement inside of each source
file, followed by any import statements then the class declaration.
a. package lab7.model or package lab7.driver
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-5
V3.1
EXempty
Step C: Impose Access Modifiers
1. Edit Profile.java. Remove the public access modifier (that is, give it the default
protection level) of Profile.authenticate(String, String). This means that only
members of the lab7.model package can see this method. If you had tightened the
access to private, then class Person would not be able to call this method from its login
method even though Person is in the same package. Save any changes.
2. Edit Test.java. Ensure that the access modifier of Test.getNextTestIdNumber() is
private. This ensures that only members of class Test may call this method. This is
desirable since the ID number sequence is a private implementation detail within class
Test. Save any changes.
Step D: Enhance the Profile Class
1. Create a new public final static String constant named REVIEWER in the Profile
class. Give it a value of "REVIEWER". This constant will be used to distinguish a new
profile privilege.
2. Save any changes.
Step E: Create a Subclass in a Separate Package
1. Create class Reviewer in package lab7.model.reviewer. Extend class Person in
package lab7.model. Import class lab7.model.Profile. The Reviewer class profile will
be given the new REVIEWER privilege.
a. Use a command prompt window, change to the lab7\model\reviewer directory.
b. Use the editor to create a file called Reviewer.
c. Edit the Reviewer file, create a Reviewer class that extends the Person class in
package lab7.model.
d. Insert the package statement lab7.model.reviewer.
e. Save the file as Reviewer.java.
2. Add the two-argument constructor that takes two String parameters. Add a call to the
superclass constructor. Copy the one from the Customer class and change Customer to
Reviewer.
3. Implement the createProfile(String, String) method inherited from the class Person.
Use the Profile.Reviewer constant to specify the REVIEWER privilege for a new
associated profile.
Our solution looks like:
public void createProfile(String theUserId, String thePassword)
{
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.REVIEWER);
setProfile(theProfile);
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-6 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
4. Save and Compile. Ensure there are no errors.
Step F: (Optional) Explore Access Modifiers
1. The createProfile(String, String) methods defined in Customer, Developer and
Reviewer work because the access modifier of the createProfile(String, String)
method in Person is public. What happens if you temporarily remove the access
modifier from method createProfile(String, String) in class Person? Does this work,
or does it cause a compiler error? It causes a compiler error, because you are
attempting to reduce the visibility of an inherited method: Java does not allow this. How
about the opposite? This works because classes can expand the visibility of a method
at the subclass level.
2. Temporarily modify the public access modifier of the Cupboard's login(String, String)
method to protected. What happens in the recompilation of lab7.driver package?
Why?
3. Restore the method to public access.
4. Save and Compile. Ensure there are no errors.
Step G: Enhance Class Cupboard
1. Add an import statement to the Cupboard class for package lab7.model.reviewer.
2. Modify the init() method to create an instance of Reviewer. Add the reviewer to the
personCollection.
3. Here is a partial solution:
...
Person aReviewer = new Reviewer("Edward", "Ed@ed.org");
aReviewer.createProfile("ED", "ED456");
...
personCollection.add(aReviewer);
...
4. Modify the listTests(Person) method of class Cupboard to list all tests if the Profile
has a privilege of REVIEWER.
Our solution looks like:
public static void listTests(Person thePerson) {
String filter = "";
if
(thePerson.getProfile().getPrivilege().equals(Profile.DEVELOPER)
)
filter = Test.DEVELOPMENT;
else
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-7
V3.1
EXempty
if
(thePerson.getProfile().getPrivilege().equals(Profile.USER))
filter = Test.PRODUCTION;
else
if
(thePerson.getProfile().getPrivilege().equals(Profile.REVIEWER))
filter = "ALL";
for (int index = 0; index < testCollection.size(); index++) {
Test theTest = (Test) testCollection.get(index);
if (theTest.getStatus().equals(filter) ||
filter.equals("ALL"))
System.out.println(
"\t"
+ theTest.getIdNumber()
+ " : "
+ theTest.getName()
+ " : "
+ theTest.getArea());
}
}
}
5. Save all changes.
Step H: Modify the Driver to Login a Reviewer
1. In the main(String[ ] args) method, use Cupboard's login(String, String) to log in the
Reviewer that you previously added in the init() method of Cupboard.
Use the same format as you did for the other persons.
Our partial solution looks like:
...
somePerson = Cupboard.login("ED", "ED456");
if (somePerson != null) {
System.out.println(
"Welcome "
+ somePerson.getName()
+ " you logged in successfully");
Cupboard.listTests(somePerson);
} else
System.out.println("Sorry, access denied");
...
2. Save any changes.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-8 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Step I: Run the Application
1. Compile the Driver class.
a. At the command prompt, make sure you are at the lab7 directory.
b. The following is the command to compile the Driver class:
javac driver\Driver.java
c. Fix any errors and compile again.
2. Execute the Driver class.
a. At the command prompt, make sure you are at the lab7 directory.
b. The following is the command to execute the driver class:
java lab7.driver.Driver
3. The following is the output you should see in the window.
Welcome Adam you logged in successfully
2 : Java Servlets : Application Development
3 : Java Applets : Application Development
5 : XML Parsers : XML
6 : Beginning HTML : Web Development
Welcome Charlene you logged in successfully
1 : Basic Java2 Syntax : Application Development
4 : XML Tags : XML
Welcome Edward you logged in successfully
1 : Basic Java2 Syntax : Application Development
2 : Java Servlets : Application Development
3 : Java Applets : Application Development
4 : XML Tags : XML
5 : XML Parsers : XML
6 : Beginning HTML : Web Development
Summary
You refactored your classes from the previous exercises into two packages. You restricted
access to some members. An optional step had you temporarily change some access
modifiers so that you could see the consequences. Access modifiers are important in
enforcing object concepts like encapsulation.
Packages are a necessity in Java to promote reusability and prevent name collisions. For
instance, as you worked through the exercises you may have noticed that you have
accumulated several classes called Profile. You kept them separated and you controlled
where they were used by making them members of uniquely named packages (lab3, lab4,
and so forth).
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-9
V3.1
EXempty
You used the import statement to tell the compiler where to search for classes. This allows
you to avoid having to use fully qualified names in the source code. It also avoids
hard-coding fully qualified names in the case where the class may need to be loaded from
another package because of modifications during development. It is easier to change an
import statement than a set of scattered fully qualified names. The import may specify
every class in a package or it may reference just one class. The import statement does not
influence bytecode size or execution speed. The import statement is only used by the
compiler to put the fully qualified name into the bytecodes. By the time the JVM loads the
class the fully qualified name is used within the bytecode.
Packages are also a unit of deployment and reuse. You could deploy your model classes
independently of our driver class. For instance, you could reuse your model classes in a
transaction based non-GUI version of our application. You could also deploy your model
package along with a presentation package that uses Swing classes to implement a GUI
version of your application.
END OF LAB
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-10 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Reference Code
package lab7.model;
import lab7.model.reviewer.*;
import lab7.model.*;
public class Cupboard {
private static java.util.Vector testCollection = new java.util.Vector();
private static java.util.Vector personCollection = new
java.util.Vector();
public static void init() {
Person thePerson = new Customer("Adam", "adam@hotmail.com");
thePerson.createProfile("ADAM", "ADAM123");
Person anotherPerson = new Developer("Charlene", "char@email.com");
anotherPerson.createProfile("CHAR", "CHAR321");
Person aReviewer = new Reviewer("Edward", "Ed@ed.org");
aReviewer.createProfile("ED", "ED456");
personCollection.add(thePerson);
personCollection.add(anotherPerson);
personCollection.add(aReviewer);
Test test1 = new Test("Basic Java2 Syntax", "Application Development");
test1.setStatus(Test.DEVELOPMENT);
Test test2 = new Test("Java Servlets", "Application Development");
test2.setStatus(Test.PRODUCTION);
Test test3 = new Test("Java Applets", "Application Development");
test3.setStatus(Test.PRODUCTION);
Test test4 = new Test("XML Tags", "XML");
test4.setStatus(Test.DEVELOPMENT);
Test test5 = new Test("XML Parsers", "XML");
test5.setStatus(Test.PRODUCTION);
Cupboard.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-11
V3.1
EXempty
Test test6 = new Test("Beginning HTML", "Web Development");
test6.setStatus(Test.PRODUCTION);
testCollection.add(test1);
testCollection.add(test2);
testCollection.add(test3);
testCollection.add(test4);
testCollection.add(test5);
testCollection.add(test6);
}
public static void listTests(Person thePerson) {
String filter = "";
if (thePerson.getProfile().getPrivilege().equals(Profile.DEVELOPER))
filter = Test.DEVELOPMENT;
else
if (thePerson.getProfile().getPrivilege().equals(Profile.USER))
filter = Test.PRODUCTION;
else
if (thePerson.getProfile().getPrivilege().equals(Profile.REVIEWER))
filter = "ALL";
for (int index = 0; index < testCollection.size(); index++) {
Test theTest = (Test) testCollection.get(index);
if (theTest.getStatus().equals(filter) || filter.equals("ALL"))
System.out.println(
"\t"
+ theTest.getIdNumber()
+ " : "
+ theTest.getName()
+ " : "
+ theTest.getArea());
}
}
public static Person login(String theUserId, String thePassword) {
Person thePerson = null;
for (int index = 0; index < personCollection.size(); index++) {
thePerson = (Person) personCollection.get(index);
if (thePerson.getProfile().getUserId().equals(theUserId))
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-12 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
break;
}
if (thePerson != null) {
boolean loggedIn = thePerson.login(theUserId, thePassword);
if (loggedIn) {
return thePerson;
}
}
return null;
}
}
package lab7.model;
public class Customer extends Person {
public Customer(String theName, String theEMail) {
super(theName, theEMail);
}
public void createProfile(String theUserId, String thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.USER);
setProfile(theProfile);
}
}
package lab7.model;
public class Developer extends Person {
public Developer(String theName, String theEMail) {
super(theName, theEMail);
}
public void createProfile(String theUserId, String thePassword) {
Customer.java
Developer.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-13
V3.1
EXempty
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.DEVELOPER);
setProfile(theProfile);
}
}
package lab7.driver;
import lab7.model.*;
import lab7.model.reviewer.*;
public class Driver {
public static void main(java.lang.String[] args) {
Cupboard.init();
Person somePerson = Cupboard.login("ADAM", "ADAM123");
if (somePerson != null) {
System.out.println(
"Welcome " + somePerson.getName() + " you logged in
successfully");
Cupboard.listTests(somePerson);
} else
System.out.println("Sorry, access denied");
somePerson = Cupboard.login("CHAR", "CHAR321");
if (somePerson != null) {
System.out.println(
"Welcome " + somePerson.getName() + " you logged in
successfully");
Cupboard.listTests(somePerson);
} else
System.out.println("Sorry, access denied");
somePerson = Cupboard.login("ED", "ED456");
if (somePerson != null) {
System.out.println(
"Welcome "
+ somePerson.getName()
+ " you logged in successfully");
Cupboard.listTests(somePerson);
} else
Driver.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-14 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
System.out.println("Sorry, access denied");
}
}
package lab7.model;
public abstract class Person {
private String name;
private String eMail;
private Profile profile;
public Person(String theName, String theEMail) {
setName(theName);
setEMail(theEMail);
}
public abstract void createProfile(String theUserId, String thePassword);
public String getEMail() {
return eMail;
}
public String getName() {
return name;
}
public Profile getProfile() {
return profile;
}
public boolean login(String theUserId, String thePassword) {
return profile.authenticate(theUserId, thePassword);
}
public void setEMail(String newEMail) {
eMail = newEMail;
}
public void setName(String newName) {
name = newName;
}
public void setProfile(Profile newProfile) {
profile = newProfile;
}
}
Person.java
Profile.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-15
V3.1
EXempty
package lab7.model;
public class Profile {
private String userId;
private String password;
private String privilege;
public final static String USER = "USER";
public final static String DEVELOPER = "DEVELOPER";
public final static String REVIEWER = "REVIEWER";
public Profile(String theUserId, String thePassword) {
setUserId(theUserId);
setPassword(thePassword);
}
boolean authenticate(String theUserId, String thePassword) {
return ((theUserId.equals(userId)) && (thePassword.equals(password)));
}
public String getPassword() {
return password;
}
public String getPrivilege() {
return privilege;
}
public String getUserId() {
return userId;
}
public void setPassword(String newPassword) {
password = newPassword;
}
public void setPrivilege(String newPrivilege) {
privilege = newPrivilege;
}
public void setUserId(String newUserId) {
userId = newUserId;
}
}
package lab7.model.reviewer;
import lab7.model.Profile;
public class Reviewer extends Person
Reviewer.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-16 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
{
public Reviewer(String theName, String theEMail)
{
super(theName,theEMail);
}
public void createProfile(String theUserId, String thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.REVIEWER);
setProfile(theProfile);
}
}
package lab7.model;
public class Test {
private String name;
private String area;
private int idNumber;
private static int NextTestIdNumber = 1;
public final static String DEVELOPMENT = "DEVELOPMENT";
public final static String PRODUCTION = "PRODUCTION";
private String status;
public Test(String theName, String theArea) {
setName(theName);
setArea(theArea);
setIdNumber(getNextTestIdNumber());
}
public String getArea() {
return area;
}
public int getIdNumber() {
return idNumber;
}
public String getName() {
return name;
}
private static int getNextTestIdNumber() {
return NextTestIdNumber++;
}
Test.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 7. Packages 7-17
V3.1
EXempty
public String getStatus() {
return status;
}
public void setArea(String newArea) {
area = newArea;
}
public void setIdNumber(int newIdNumber) {
idNumber = newIdNumber;
}
public void setName(String newName) {
name = newName;
}
public void setStatus(String newStatus) {
status = newStatus;
}
}
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
7-18 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-1
V3.1
EXempty
Exercise 8. Simple I/O and Exceptions
What This Exercise Is About
In this exercise you will handle an exception using an I/O example.
The UML class diagrams shown below are the same as those in the
previous exercise. You will change only the implementation of one
method.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
3HUVRQ
-name : String
-eMail : String
-profile : Profile
+Person()
+Person(String,String)
+createProfile(String,String) : void
+getEmail() : String
+getName() : String
+getProfile() : String
+login(String, String) : boolean
+setEmail(String) : void
+setName(String) : void
+setProfile(Profile) : void
ProfiIe
+DEVELOPER : String = "DEVELOPER"
+REVEWER : String = "REVEWER"
+USER : String = "USER"
-password : String
-privilege : String
-userd : String
+Profile(String,String)
+Profile()
~authenticate(String,String) : boolean
+getPassword() : String
+getPrivilege() : String
+getUserd() : String
+setPassword(String) : void
+setPrivilege(String) : void
+setUserd(String) : void
Driver
+main(String[]) : void
Cupboard
-personCollection : Vector
-testCollection : Vector
+init() : void
+listTests(Person) : void
+login(String,String) : Person
Test
+DEVELOPMENT : String = "DEVELOPMENT"
+PRODUCTON : String = "PRODUCTON"
-nextdNumber : int = 1
-name : String
-area : String
-idNumber : int
-status : String
+Test()
+Test(String,String)
+getArea() : String
+getdNumber() : int
+getName : String
-getNextTestdNumber() : int
+getStatus() : String
+setArea(String) : void
+setdNumber(int) : void
+setName(String) : void
+setStatus(String) : void
Customer
+Customer(String,String)
+Customer()
+createProfile(String,String) : void
DeveIoper
+Developer(String,String)
+Developer()
+createProfile(String,String) : void
Reviewer
+Reviewer()
+Reviewer(String,String)
+createProfile(String,String) : void
1
0..n
0..n
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-3
V3.1
EXempty What You Should Be Able to Do
At the end of the lab, you should be able to:
Handle an I/O exception in code
Required Materials
Sun J2SE SDK 1.4.2
Windows Notepad or equivalent
Solutions to model, model.reviewer, and driver (Packages
exercise)
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Exercise Instructions
The previous exercises had you hard-coding customers, reviewers, and developers and
storing them in a collection of persons. You also hardcoded tests and stored them in a
collection of tests. Now you will initialize those collections from a file. You will modify only
the init() method of class Cupboard.
When a program carries out an I/O operation it must include an exception handler, to
handle the situation when an error occurs. The checked code is wrapped in a Java try
block. The exception handler or handlers are specified and implemented by one or more
catch blocks. Each catch block specifies an input parameter of the desired exception type
-- java.io.IOException in this exercise. The parameter is a reference to an instance of an
exception.
You will use a BufferedReader composed of a FileReader to read the input file with a
readLine() method.
Directions
Step A: Create Packages
1. Under a command prompt window, create a new model directory beneath
C:\OOPwJava\lab8. This directory will contain the Cupboard, Customer, Developer,
Person, Profile, and Test classes. This will now be known as the model package.
2. Under a command prompt window, create a new reviewer directory beneath
C:\OOPwJava\lab8\model. This will contain a Reviewer class. This will now be known
as the model.reviewer package.
3. Under a command prompt window, create a new driver directory beneath
C:\OOPwJava\lab8. This directory will contain the Driver class. This will now be known
as the driver package.
Step B: Reuse Existing Classes
1. Copy the Cupboard, Customer, Developer, Person, Profile, and Test classes from
lab7\model to your new lab8\model directory.
2. Copy the Driver class from lab7\driver to your new lab8\driver directory.
3. Copy the Reviewer class from lab7\model\reviewer to your new lab8\model\reviewer
directory.
4. Change all package and import statements to reflect lab8 instead of lab7.
5. Save any changes.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-5
V3.1
EXempty
Step C: Create an Initialization File for Use by Cupboard.init()
In this step you will replace the hard-coding you used to initialize the Cupboard with data in
external files. These files already exist in the solution directory. The following steps explain
the creation process.
1. In the lab8 directory, create a persons.txt file. Populate the file with successive text
lines that contain, in turn: name, email, user id, password, privilege. Ensure that you
have at least one person representing each of these privileges: DEVELOPER, USER,
or REVIEWER. Here are contents of our persons.txt file that can be copied from the
lab8 solution directory:
Adam
adam@hotmail.com
ADAM
ADAM123
USER
Charlene
char@email.com
CHAR
CHAR321
DEVELOPER
Edward
Ed@ed.org
ED
ED456
REVIEWER
2. In the directory lab8, create a tests.txt file. The format for the tests.txt file is successive
text lines that contain, in turn: name, area, and status. The latter value is either
PRODUCTION or DEVELOPMENT. Here are the contents of our tests.txt file that can
be copied from the lab8 solution directory:
Basic Java2 Syntax
Application Development
DEVELOPMENT
Java Servlets
Application Development
PRODUCTION
Java Applets
Application Development
PRODUCTION
XML Tags
XML
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-6 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
DEVELOPMENT
XML Parsers
XML
PRODUCTION
Beginning HTML
Web Development
PRODUCTION
Step D: Modify the Cupboard.init() Method to Use File I/O
1. Import package java.io into the Cupboard class.
a. Add the statement import java.io.*; either before or after the import statement
for model.reviewer.*;
2. Comment out the code that currently exists inside the init() method of the Cupboard
class.
a. Prior to the first line of code type a "/*"
b. After the last line of code type a "*/*
3. Create a try block followed directly by a catch block and a finally clause. The catch
block should catch IOException. Within the catch block, print a stack trace and exit the
JVM.
Our try block looks like:
try {
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
System.exit(1);
} finally {
}
4. Just before the try block you need to create a reference to a BufferedReader and
initialize it to null. Within the try block, create a BufferedReader from a FileReader
initialized with the persons.txt file and store that in the BufferedReader references you
created earlier. In a later step you will also be reading the tests.txt file from the same
directory where persons.txt resides. To take care of this you need to create a new
String, prefix, that is initialized to the lab8 solution directory where the persons.txt and
tests.txt files reside.
Our solution:
String prefix = C:\\OOPwJava\\lab8\\solution\\;
BufferedReader personReader = null;
try {
personReader = new BufferedReader(
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-7
V3.1
EXempty
new FileReader(prefix + "persons.txt"));
Information: This solution is not the ideal one. Hard coding file names and
directories in your application can lead to both deployment and maintenance issues.
Also the syntax we have used ties our application to a Windows environment. An
alternative would be to use properties files or the class loader getResources support
to add flexibility to the application. Since we are only focused on the I/O classes right
now we have taken a more direct, but less than ideal, approach.
We will be reading two files (persons.txt and tests.txt) from the
C:\OOPwJava\lab8\solution directory. We created the prefix string so we dont have
to hard code the directory structure twice in the code.
5. After creating the BufferedReader, but still within the try block, code a while block.
Have it loop as long as the readLine() method for name returns a none-null value.
Within the while loop, read five lines into name, email, userId, password, and
privilege String variables. The code for the following steps should be placed within the
while block until directed otherwise.
Our solution:
String name = null;
while ((name = personReader.readLine()) != null) {
String eMail = personReader.readLine();
String userId = personReader.readLine();
String password = personReader.readLine();
String privilege = personReader.readLine();
Person thePerson = null;
6. Create a new Customer, Developer, or Reviewer based upon the value read into the
privilege variable. Pass the values of name and email. Assign the new instance to a
Person variable named thePerson.
Our Solution:
if (privilege.equals("USER"))
thePerson = new Customer(name, eMail);
if (privilege.equals("DEVELOPER"))
thePerson = new Developer(name, eMail);
if (privilege.equals("REVIEWER"))
thePerson = new Reviewer(name, eMail);
7. Create a new profile for the Person by calling its createProfile method. Pass userId
and password.
Our solution:
thePerson.createProfile(userId, password);
8. Add the new person to the Cupboard's person collection.
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-8 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Our solution:
personCollection.add(thePerson);
9. Close the while block with a curly right brace.
10. In the final clause of your try block close the BufferedReader using its close() method.
You need to make sure the input reader is not null and you need to enclose the close in
a try bock.
Our solution:
} finally{
try {
if (personReader != null) {
personReader.close();
}
} catch (IOException ioe2) {
}
}
11. Save the init() method.
Step E: Load the Test Collection into the Cupboard
In this step, you will again modify the init() method of Cupboard. You will read the data
from your tests.txt file. This time it will be slightly easier because Test is a less complicated
class.
1. After the final block (from reading in the persons), create new try / catch / finally blocks
as before. Handle java.io.Exception exactly as before.
2. Create a new BufferedReader passing it a new FileReader created on the file name
tests.txt.
3. Create a while((name = testReader.readLine()) != null) { ... } block
within the new try block as before.
4. Within the while block, read successive lines into String variables name, area, and
status, respectively.
5. Create a new Test instance using the name and area variables.
6. Set the status of the new Test instance using the status variable.
7. Add the new Test instance to the testCollection of Cupboard.
8. Close the while block with a curly brace.
9. Still within the try block, close the BufferedReader.
10. Save the init() method, fix any compile errors.
Here is our complete solution to the init() method of Cupboard:
public static void init() {
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-9
V3.1
EXempty
String prefix = C:\\OOPwJava\\lab8\\solution\\;
BufferedReader personReader = null;
try {
personReader = new BufferedReader(new FileReader(prefix +
"persons.txt"));
String name = null;
while ((name = personReader.readLine()) != null)
String eMail = personReader.readLine();
String userId = personReader.readLine();
String password = personReader.readLine();
String privilege = personReader.readLine();
Person thePerson = null;
if (privilege.equals("USER"))
thePerson = new Customer(name, eMail);
if (privilege.equals("DEVELOPER"))
thePerson = new Developer(name, eMail);
if (privilege.equals("REVIEWER"))
thePerson = new Reviewer(name, eMail);
thePerson.createProfile(userId, password);
personCollection.add(thePerson);
}
}catch (java.io.IOException ioe) {
ioe.printStackTrace();
System.exit(1);
} finally {
try{
if (personReader != null) {
personReader.close();
}
} catch (IOException ioe2) {}
}
BufferedReader testReader = null;
try {
testReader = new BufferedReader(new FileReader(prefix +
"tests.txt"));
String name = null;
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-10 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
while ((name = testReader.readLine()) != null)
String area = testReader.readLine();
String status = testReader.readLine();
Test theTest = new Test(name, area);
theTest.setStatus(status);
testCollection.add(theTest);
}
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
System.exit(1);
}finally {
try{
if (testReader != null) {
testReader.close();
}
} catch (IOException ioe2) {}
}
}
Step F: Test the Code
1. Compile using C:\OOPwJava\lab8>javac driver\Driver.java. Check for errors. Fix them
before running.
2. Execute the Driver class using C:\OOPwJava\lab8>java lab8.driver.Driver. Output
should be the same as the previous exercise, provided that the input data and the main
implementation are the same.
Summary
You added I/O to the application and had to write code to handle a java.io.IOException, a
checked exception. This means that the compiler enforces the handling of the exception.
You must either enclose the code in a try/catch block or specify that the method throws that
exception to any caller. Such a caller would either handle the exception in a try / catch
block or throw the exception in turn.
A non-checked exception has no mandatory handling specified. Handling or throwing is up
to the programmer. An example of a common non-checked exception is a
java.lang.ArrayIndexOutOfBoundsException. A program may overrun an array boundary
without explicitly handling or throwing this exception. In this case, if it is thrown, the
exception percolates up to the JVM as an uncaught exception.
END OF LAB
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-11
V3.1
EXempty
Reference Code
package lab8.model;
import lab8.model.reviewer.*;
import lab8.model.*;
import java.io.*;
public class Cupboard {
private static java.util.Vector testCollection = new java.util.Vector();
private static java.util.Vector personCollection = new
java.util.Vector();
public static void init() {
String prefix = C:\\OOPwJava\\lab8\\solution;
BufferedReader personReader = null;
try {
personReader = new BufferedReader(new FileReader(prefix +
"persons.txt"));
String name = null;
while ((name = personReader.readLine()) != null)
String eMail = personReader.readLine();
String userId = personReader.readLine();
String password = personReader.readLine();
String privilege = personReader.readLine();
Person thePerson = null;
if (privilege.equals("USER"))
thePerson = new Customer(name, eMail);
if (privilege.equals("DEVELOPER"))
thePerson = new Developer(name, eMail);
if (privilege.equals("REVIEWER"))
thePerson = new Reviewer(name, eMail);
thePerson.createProfile(userId, password);
personCollection.add(thePerson);
}
} catch (java.io.IOException ioe) {
Cupboard.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-12 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
ioe.printStackTrace();
System.exit(1);
} finally {
try{
if (personReader != null) {
personReader.close();
}
} catch (IOException ioe2) {}
}
BufferedReader testReader = null;
try {
testReader = new BufferedReader(new FileReader(
prefix + "tests.txt"));
String name = null;
while ((name = testReader.readLine()) != null)
String area = testReader.readLine();
String status = testReader.readLine();
Test theTest = new Test(name, area);
theTest.setStatus(status);
testCollection.add(theTest);
}
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
System.exit(1);
} finally {
try{
if (personReader != null) {
personReader.close();
}
} catch (IOException ioe2) {}
}
}
public static void listTests(Person thePerson) {
String filter = "";
if (thePerson.getProfile().getPrivilege().equals(Profile.DEVELOPER))
filter = Test.DEVELOPMENT;
else
if (thePerson.getProfile().getPrivilege().equals(Profile.USER))
filter = Test.PRODUCTION;
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-13
V3.1
EXempty
else
if (thePerson.getProfile().getPrivilege().equals(Profile.REVIEWER))
filter = "ALL";
for (int index = 0; index < testCollection.size(); index++) {
Test theTest = (Test) testCollection.get(index);
if (theTest.getStatus().equals(filter) || filter.equals("ALL"))
System.out.println(
"\t"
+ theTest.getIdNumber()
+ " : "
+ theTest.getName()
+ " : "
+ theTest.getArea());
}
}
public static Person login(String theUserId, String thePassword) {
Person thePerson = null;
for (int index = 0; index < personCollection.size(); index++) {
thePerson = (Person) personCollection.get(index);
if (thePerson.getProfile().getUserId().equals(theUserId))
break;
}
if (thePerson != null) {
boolean loggedIn = thePerson.login(theUserId, thePassword);
if (loggedIn) {
return thePerson;
}
}
return null;
}
}
package lab8.model;
public class Customer extends Person {
Customer.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-14 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
public Customer(String theName, String theEMail) {
super(theName, theEMail);
}
public void createProfile(String theUserId, String thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.USER);
setProfile(theProfile);
}
}
package lab8.model;
public class Developer extends Person {
public Developer(String theName, String theEMail) {
super(theName, theEMail);
}
public void createProfile(String theUserId, String thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.DEVELOPER);
setProfile(theProfile);
}
}
package lab8.driver;
import lab8.model.*;
import lab8.model.reviewer.*;
public class Driver {
public static void main(java.lang.String[] args) {
Cupboard.init();
Person somePerson = Cupboard.login("ADAM", "ADAM123");
if (somePerson != null) {
System.out.println(
"Welcome " + somePerson.getName() + " you logged in
successfully");
Developer.java
Driver.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-15
V3.1
EXempty
Cupboard.listTests(somePerson);
} else
System.out.println("Sorry, access denied");
somePerson = Cupboard.login("CHAR", "CHAR321");
if (somePerson != null) {
System.out.println(
"Welcome " + somePerson.getName() + " you logged in
successfully");
Cupboard.listTests(somePerson);
} else
System.out.println("Sorry, access denied");
somePerson = Cupboard.login("ED", "ED456");
if (somePerson != null) {
System.out.println(
"Welcome "
+ somePerson.getName()
+ " you logged in successfully");
Cupboard.listTests(somePerson);
} else
System.out.println("Sorry, access denied");
}
}
package lab8.model;
public abstract class Person {
private String name;
private String eMail;
private Profile profile;
public Person(String theName, String theEMail) {
setName(theName);
setEMail(theEMail);
}
public abstract void createProfile(String theUserId, String thePassword);
public String getEMail() {
return eMail;
}
public String getName() {
return name;
Person.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-16 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
}
public Profile getProfile() {
return profile;
}
public boolean login(String theUserId, String thePassword) {
return profile.authenticate(theUserId, thePassword);
}
public void setEMail(String newEMail) {
eMail = newEMail;
}
public void setName(String newName) {
name = newName;
}
public void setProfile(Profile newProfile) {
profile = newProfile;
}
}
package lab8.model;
public class Profile {
private String userId;
private String password;
private String privilege;
public final static String USER = "USER";
public final static String DEVELOPER = "DEVELOPER";
public final static String REVIEWER = "REVIEWER";
public Profile(String theUserId, String thePassword) {
setUserId(theUserId);
setPassword(thePassword);
}
boolean authenticate(String theUserId, String thePassword) {
return ((theUserId.equals(userId)) && (thePassword.equals(password)));
}
public String getPassword() {
return password;
}
public String getPrivilege() {
return privilege;
}
public String getUserId() {
Profile.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-17
V3.1
EXempty
return userId;
}
public void setPassword(String newPassword) {
password = newPassword;
}
public void setPrivilege(String newPrivilege) {
privilege = newPrivilege;
}
public void setUserId(String newUserId) {
userId = newUserId;
}
}
package lab8.model.reviewer;
import lab8.model.Profile;
public class Reviewer extends Person
{
public Reviewer(String theName, String theEMail)
{
super(theName,theEMail);
}
public void createProfile(String theUserId, String thePassword) {
Profile theProfile = new Profile(theUserId, thePassword);
theProfile.setPrivilege(Profile.REVIEWER);
setProfile(theProfile);
}
}
package lab8.model;
public class Test {
private String name;
private String area;
private int idNumber;
private static int NextTestIdNumber = 1;
public final static String DEVELOPMENT = "DEVELOPMENT";
public final static String PRODUCTION = "PRODUCTION";
Reviewer.java
Test.java
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-18 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
private java.lang.String status;
public Test(String theName, String theArea) {
setName(theName);
setArea(theArea);
setIdNumber(getNextTestIdNumber());
}
public String getArea() {
return area;
}
public int getIdNumber() {
return idNumber;
}
public String getName() {
return name;
}
private static int getNextTestIdNumber() {
return NextTestIdNumber++;
}
public String getStatus() {
return status;
}
public void setArea(String newArea) {
area = newArea;
}
public void setIdNumber(int newIdNumber) {
idNumber = newIdNumber;
}
public void setName(String newName) {
name = newName;
}
public void setStatus(String newStatus) {
status = newStatus;
}
}
Adam
adam@hotmail.com
ADAM
ADAM123
USER
Charlene
Person.txt
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 8. Simple I/O and Exceptions 8-19
V3.1
EXempty
char@email.com
CHAR
CHAR321
DEVELOPER
Edward
Ed@ed.org
ED
ED456
REVIEWER
Basic Java2 Syntax
Application Development
DEVELOPMENT
Java Servlets
Application Development
PRODUCTION
Java Applets
Application Development
PRODUCTION
XML Tags
XML
DEVELOPMENT
XML Parsers
XML
PRODUCTION
Beginning HTML
Web Development
PRODUCTION
tests.txt
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
8-20 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
V3.1
backpg
Back page

Вам также может понравиться