Java Reference
In-Depth Information
The top box in the UML diagram contains the name of the class. The middle box
contains the data members and their data types. The last box contains the method names,
parameter list, and return types. The + (plus) sign in front of a member indicates that it is a
public member; the - (minus) sign indicates that it is a private member. The # symbol
before a member name indicates that it is a protected member.
Variable Declaration and Object Instantiation
Once a class is defined, you can declare reference variables of that class type. For
example, the following statements declare myClock and yourClock to be reference
variables of type Clock :
Clock myClock;
//Line 1
Clock yourClock;
//Line 2
These statements do not allocate memory spaces to store the hours, minutes, and seconds.
Next, we explain how to allocate memory space to store the hours, minutes, and seconds,
and how to access that memory space using the variables myClock and yourClock .
The class Clock has three instance variables. To store the hours, minutes, and seconds,
we need to create a Clock object, which is accomplished by using the operator new .
The general syntax for using the operator new is:
8
new className()
//Line 3
or:
new className(argument1, argument2, ..., argumentN)
//Line 4
The expression in Line 3 instantiates the object and initializes the instance variables of the
object using the default constructor. The expression in Line 4 instantiates the object and
initializes the instance variables using a constructor with parameters.
For the expression in Line 4:
￿ The number of arguments and their type should match the formal
parameters (in the order given) of one of the constructors.
￿ If the type of the arguments does not match the formal parameters of any
constructor (in the order given), Java uses type conversion and looks for
the best match. For example, an integer value might be converted to a
floating-point value with a zero decimal part. Any ambiguity will result
in a compile-time error.
Consider the following statements (notice that myClock and yourClock are as declared
in Lines 1 and 2):
myClock = new Clock();
//Line 5
yourClock = new Clock(9, 35, 15);
//Line 6
 
Search WWH ::




Custom Search