Java Reference
In-Depth Information
System.out.println("Line 14: After again rolling "
+ "the sum of the numbers rolled is: "
+ (die1.roll() + die2.roll()));
//Line 14
}
//end main
//Line 15
}
//Line 16
Sample Run:
Line 9: die1: 1
Line 10: die2: 1
Line 11: After rolling die1: 5
Line 12: After rolling die2: 3
Line 13: Sum of the numbers rolled by the dice is: 8
Line 14: After again rolling the sum of the numbers rolled is: 4
The preceding program works as follows. The statements in Lines 7 and 8 create the
objects
die1
and
die2
, and using the default constructor set both the dice to 1. The
statements in Lines 9 and 10 output the number of both the dice. The statement in Line
11 rolls
die1
and outputs the number rolled. Similarly, the statement in Line 12 rolls
die2
and outputs the number rolled. The statement in Line 13 outputs the sum of the
numbers rolled by
die1
and
die2
. The statement in Line 14 again rolls both the dice and
outputs the sum of the numbers rolled.
Copy Constructor
Suppose that you have the following statement:
Clock myClock =
new
Clock(8, 45, 22);
//Line 1
You can use the object
myClock
to declare and instantiate another
Clock
object.
Consider the following statement:
Clock aClock =
new
Clock(myClock);
//Line 2
This statement declares
aClock
to be a reference variable of type
Clock
, instantiates the
object
aClock
, and initializes the instance variables of the object
aClock
using the values
of the corresponding instance variables of the object
myClock
. However, to successfully
execute the statement in Line 2, you need to include a special constructor, called a copy
constructor, in the
class
Clock
. The copy constructor executes when an object is
instantiated and initialized using an existing object.
The syntax of the heading of the copy constructor is:
public
ClassName(ClassName otherObject)
For example, the heading of the copy constructor for the
class
Clock
is:
public
Clock(Clock otherClock)
Search WWH ::
Custom Search