Java Reference
In-Depth Information
In all of our previous examples, we've written a single class containing a single
main
method. These classes represent small but complete programs. These pro-
grams often instantiated objects using predefined classes from the Java class
library and used those objects for the services they provide. Those predefined
classes are part of the program too, but we never really concern ourselves with
them other than to know how to interact with them. We simply trust them to
provide the services they promise.
Let's look at another, similar example. The
RollingDice
class shown in
Listing 4.1 contains a
main
method that instantiates two
Die
objects (as in the
singular of dice). It then rolls the dice and prints the results. It also calls several
other methods provided by the
Die
class, such as the ability to explicitly set and
get the current face value of a die.
LISTING 4.1
//********************************************************************
// RollingDice.java Author: Lewis/Loftus
//
// Demonstrates the creation and use of a user-defined class.
//********************************************************************
public class
RollingDice
{
//-----------------------------------------------------------------
// Creates two Die objects and rolls them several times.
//-----------------------------------------------------------------
public static void
main (String[] args)
{
Die die1, die2;
int
sum;
die1 =
new
Die();
die2 =
new
Die();
die1.roll();
die2.roll();
System.out.println ("Die One: " + die1 + ", Die Two: " + die2);
die1.roll();
die2.setFaceValue(4);
Search WWH ::
Custom Search