Java Reference
In-Depth Information
LISTING 4.1
continued
System.out.println ("Die One: " + die1 + ", Die Two: " + die2);
sum = die1.getFaceValue() + die2.getFaceValue();
System.out.println ("Sum: " + sum);
sum = die1.roll() + die2.roll();
System.out.println ("Die One: " + die1 + ", Die Two: " + die2);
System.out.println ("New sum: " + sum);
}
}
OUTPUT
Die One: 5, Die Two: 2
Die One: 1, Die Two: 4
Sum: 5
Die One: 4, Die Two: 2
New sum: 6
The primary difference between this example and previous examples is that the
Die class is not a predefined part of the Java class library. We have to write the
Die class ourselves, defining the services we want Die objects to perform, if this
program is to compile and run.
Every class can contain data declarations and method declarations, as depicted
in Figure 4.2. The data declarations represent the data that will be stored in each
object of the class. The method declarations define the services that those objects
will provide. Collectively, the data and methods of a class are called the members
of a class.
The classes we've written in previous examples follow this model as well, but
contain no data at the class level and contain only one method (the main method).
We'll continue to define classes like this, such as the RollingDice class, to define
the starting point of a program.
True object-oriented programming, however, comes from defining classes
that represent objects with well-defined state and behavior. For
example, at any given moment a Die object is showing a particular
face value, which we could refer to as the state of the die. A Die
object also has various methods we can invoke on it, such as the
ability to roll the die or get its face value. These methods represent
the behavior of a die.
KEY CONCEPT
The heart of object-oriented pro-
gramming is defining classes that
represent objects with well-defined
state and behavior.
 
Search WWH ::




Custom Search