AhmadLang / Java, How To Program, 2004
.pdf
[View full size image]
The class diagram in Fig. 6.25 specifies that operation dispenseCash of class CashDispenser takes a Double parameter amount to indicate the amount of cash (in dollars) to be dispensed. Operation isSufficientCashAvailable also takes a Double parameter amount to indicate the amount of cash in question.
Figure 6.25. Class CashDispenser with operation parameters.
(This item is displayed on page 270 in the print version)
[View full size image]
[Page 270]
Note that we do not discuss parameters for operation execute of classes BalanceInquiry, Withdrawal and Deposit, operation getInput of class Keypad and operation isEnvelopeReceived of class DepositSlot. At this point in our design process, we cannot determine whether these operations require additional data to perform their tasks, so we leave their parameter lists empty. As we progress through the case study, we may decide to add parameters to these operations.
In this section, we have determined many of the operations performed by the classes in the ATM system. We have identified the parameters and return types of some of the operations. As we continue our design process, the number of operations belonging to each class may varywe might find that new operations are needed or that some current operations are unnecessaryand we might determine that some of our class operations need additional parameters and different return types.
Software Engineering Case Study Self-Review Exercises
6.1 Which of the following is not a behavior?
a.reading data from a file
b.printing output
c.text output
d.obtaining input from the user
6.2 If you were to add to the ATM system an operation that returns the amount attribute of class Withdrawal, how and where would you specify this operation in the class diagram of Fig. 6.21?
6.3 Describe the meaning of the following operation listing that might appear in a class diagram for an object-oriented design of a calculator:
add( x : Integer, y : Integer ) : Integer
Answers to Software Engineering Case Study Self-Review Exercises
6.1 c.
6.2 To specify an operation that retrieves the amount attribute of class Withdrawal, the following operation listing would be placed in the operation (i.e., third) compartment of class Withdrawal:
getAmount( ) : Double
[Page 271]
6.3 This operation listing indicates an operation named add that takes integers x and y as parameters and returns an integer value.
[Page 271 (continued)]
6.15. Wrap-Up
In this chapter, you learned more about the details of method declarations. You also learned the difference between non-static and static methods and how to call static methods by preceding the method name with the name of the class in which it appears and a dot (.). You learned how to use operator + to perform string concatenations. You learned how to declare named constants using both enum types and public final static variables. You saw how to use class Random to generate sets of random numbers that can be used for simulations. You also learned about the scope of fields and local variables in a class. Finally, you learned that multiple methods in one class can be overloaded by providing methods with the same name and different signatures. Such methods can be used to perform the same or similar tasks using different types or different numbers of parameters.
In Chapter 7, you will learn how to maintain lists and tables of data in arrays. You will see a more elegant implementation of the application that rolls a die 6000 times and two enhanced versions of our GradeBook case study that you studied in Chapters 35. You will also learn how to access an application's command-line arguments that are passed to method main when an application begins execution.
[Page 271 (continued)]
Summary
Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces, or modules. This technique is called divide and conquer.
There are three kinds of modules in Javamethods, classes and packages. Methods are declared
within classes. Classes are typically grouped into packages so that they can be imported into programs and reused.
Methods allow the programmer to modularize a program by separating its tasks into self-
contained units. The statements in a method are written only once and hidden from other methods.
Using existing methods as building blocks to create new programs is a form of software reusability that allows programmers to avoid repeating code within a program.
A method call specifies the name of the method to call and provides the arguments that the
called method requires to perform its task. When the method call completes, the method returns either a result or simply control to its caller.
A class may contain static methods to perform common tasks that do not require an object of
the class. Any data a static method might require to perform its tasks can be sent to the method as arguments in a method call. A static method is called by specifying the name of the class in which the method is declared followed by a dot (.) and the method name, as in
ClassName. methodName( arguments )
Method arguments may be constants, variables or expressions.
Class Math provides static methods for performing common mathematical calculations. Class
Math declares two fields that represent commonly used mathematical constants: Math.PI and Math.E. The constant Math.PI (3.14159265358979323846) is the ratio of a circle's circumference to its diameter. The constant Math.E (2.7182818284590452354) is the base value for natural logarithms (calculated with static Math method log).
[Page 272]
Math.PI and Math.E are declared with the modifiers public, final and static. Making them
public allows other programmers to use these fields in their own classes. Any field declared with keyword final is constantits value cannot be changed after the field is initialized. Both PI and E are declared final because their values never change. Making these fields static allows them to be accessed via the class name Math and a dot (.) separator, just like class Math's methods.
When objects of a class containing static fields (class variables) are created, all the objects of
that class share one copy of the class's static fields. Together the class variables and instance variables represent the fields of a class. You will learn more about static fields in Section 8.11.
When you execute the Java Virtual Machine (JVM) with the java command, the JVM attempts to
invoke the main method of the class you specify. The JVM loads the class specified by ClassName and uses that class name to invoke method main. You can specify an optional list of Strings (separated by spaces) as command-line arguments that the JVM will pass to your application.
You can place a main method in every class you declareonly the main method in the class you
use to execute the application will be called. Some programmers take advantage of this to build a small test program into each class they declare.
When a method is called, the program makes a copy of the method's argument values and
assigns them to the method's corresponding parameters, which are created and initialized when the method is called. When program control returns to the point in the program where the method was called, the method's parameters are removed from memory.
A method can return at most one value, but the returned value could be a reference to an object that contains many values.
Variables should be declared as fields of a class only if they are required for use in more than
one method of the class or if the program should save their values between calls to the class's methods.
There are three ways to call a methodusing a method name by itself to call another method of
the same class; using a variable that contains a reference to an object, followed by a dot (.) and the method name to call a method of the referenced object; and using the class name and a dot (.) to call a static method of a class.
There are three ways to return control to a statement that calls a method. If the method does
not return a result, control returns when the program flow reaches the method-ending right brace or when the statement
return;
is executed. If the method returns a result, the statement
return expression;
evaluates the expression, then immediately returns the resulting value to the caller.
When a method has more than one parameter, the parameters are specified as a comma-
separated list. There must be one argument in the method call for each parameter in the method declaration. Also, each argument must be consistent with the type of the corresponding parameter. If a method does not accept arguments, the parameter list is empty.
Strings can be concatenated using operator +, which places the characters of the right operand at the end of those in the left operand.
Every primitive value and object in Java has a String representation. When an object is
concatenated with a String, the object is converted to a String, then the two Strings are concatenated.
For primitive values used in string concatenation, the JVM handles the conversion of the primitive
values to Strings. If a boolean is concatenated with a String, the word "TRue" or the word "false" is used to represent the boolean value. If there are any trailing zeros in a floating-point value, these will be discarded when the number is concatenated to a String.
[Page 273]
All objects in Java have a special method named toString that returns a String representation
of the object's contents. When an object is concatenated with a String, the JVM implicitly calls the object's toString method to obtain the string representation of the object.
When a large String literal is typed into a program's source code, programmers sometimes
break that String into several smaller Strings and place them on multiple lines of code for readability, then reassemble the Strings using concatenation.
Stacks are known as last-in, first-out (LIFO) data structuresthe last item pushed (inserted) on the stack is the first item popped (removed) from the stack.
A called method must know how to return to its caller, so the return address of the calling
method is pushed onto the program execution stack when the method is called. If a series of method calls occurs, the successive return addresses are pushed onto the stack in last-in, firstout order so that the last method to execute will be the first to return to its caller.
The program execution stack contains the memory for the local variables used in each invocation
of a method during a program's execution. This data is known as the activation record or stack frame of the method call. When a method call is made, the activation record for that method call is pushed onto the program execution stack. When the method returns to its caller, the activation record for this method call is popped off the stack and those local variables are no longer known to the program. If a local variable holding a reference to an object is the only variable in the program with a reference to that object, when the activation record containing that local variable is popped off the stack, the object can no longer be accessed by the program and will eventually be deleted from memory by the JVM during "garbage collection."
The amount of memory in a computer is finite, so only a certain amount of memory can be used
to store activation records on the program execution stack. If there are more method calls than can have their activation records stored on the program execution stack, an error known as a stack overflow occurs. The application will compile correctly, but its execution causes a stack overflow.
An important feature of method calls is argument promotionconverting an argument's value to the type that the method expects to receive in its corresponding parameter.
A set of promotion rules apply to expressions containing values of two or more primitive types
and to primitive-type values passed as arguments to methods. Each value is promoted to the "highest" type in the expression. In cases where information may be lost due to conversion, the Java compiler requires the programmer to use a cast operator to explicitly force the conversion to occur.
Objects of class Random (package java.util) can produce random int, long, float or double
values. Math method random can produce double values in the range 0.0 < x < 1.0, where x is the value returned by method random.
Random method nextInt generates a random int value in the range 2,147,483,648 to
+2,147,483,647. The values returned by nextInt are actually pseudorandom numbersa sequence of values produced by a complex mathematical calculation. That calculation uses the current time of day to seed the random-number generator such that each execution of a program yields a different sequence of random values.
Class Random provides another version of method nextInt that receives an int argument and returns a value from 0 up to, but not including, the argument's value.
Random numbers in a range can be generated with
number = shiftingValue + randomNumbers.nextInt( scalingFactor );
where shiftingValue specifies the first number in the desired range of consecutive integers, and scalingFactor specifies how many numbers are in the range.
[Page 274]
Random numbers can be chosen from nonconsecutive integer ranges, as in
number = shiftingValue +
differenceBetweenValues * randomNumbers.nextInt( scalingFactor );
where shiftingValue specifies the first number in the range of values, differenceBetweenValues represents the difference between consecutive numbers in the sequence and scalingFactor specifies how many numbers are in the range.
For debugging, it is sometimes useful to repeat the same sequence of pseudorandom numbers
during each program execution to prove that your application is working for a specific sequence of random numbers before testing the program with different sequences of random numbers. When repeatability is important, you can create a Random object by passing a long integer value to the constructor. If the same seed is used every time the program executes, the Random object produces the same sequence of random numbers. You can also set a Random object's seed at any
time by calling the object's setSeed method.
An enumeration is introduced by the keyword enum (new to J2SE 5.0) and a type name. As with
any class, braces ({ and }) delimit the body of an enum declaration. Inside the braces is a comma-separated list of enumeration constants, each representing a unique value. The identifiers in an enum must be unique. Variables of an enum type can be assigned only constants of that enum type.
Constants can also be declared as public final static variables. Such constants are declared with all capital letters by convention to make them stand out in the program.
Scope is the portion of the program in which an entity, such as a variable or a method, can be referred to by its name. Such an entity is said to be "in scope" for that portion of the program.
The scope of a parameter declaration is the body of the method in which the declaration appears.
The scope of a local-variable declaration is from the point at which the declaration appears to the end of that block.
The scope of a label in a labeled break or continue statement is the labeled statement's body.
The scope of a local-variable declaration that appears in the initialization section of a for statement's header is the body of the for statement and the other expressions in the header.
The scope of a method or field of a class is the entire body of the class. This enables a class's methods to use simple names to call the class's other methods and to access the class's fields.
Any block may contain variable declarations. If a local variable or parameter in a method has the same name as a field, the field is shadowed until the block terminates execution.
Java allows several methods of the same name to be declared in a class, as long as the
methods have different sets of parameters (determined by the number, order and types of the parameters). This technique is called method overloading.
Overloaded methods are distinguished by their signaturescombinations of the methods' names
and the number, types and order of their parameters. Methods cannot be distinguished by return type.
[Page 274 (continued)]
Terminology
activation record
application programming interface argument promotion
block
class variable class method
comma-separated list of parameters command-line argument divide-and-conquer approach element of chance
enum keyword
enumeration
[Page 275]
enumeration constant final keyword formal parameter function
"hidden" fields
hide implementation details
hierarchical boss method/worker method relationship invoke a method
Java API documentation
Java Application Programming Interface (API) last-in, first-out (LIFO) data structure
local variable
