Information Technology Reference
In-Depth Information
In the code segment above, classes representing dice with different numbers of
sides are created using an abstract base class Die . In the base class, one attribute and
one method are defined. The attribute, sides , is an integer that denotes the number
of sides on a die. Note that this attribute is only declared in our base class, and is not
assigned a value. The method defined in the base class is roll , which takes
advantage of Java's Math.random method to select a random integer between 1
and the number denoted by the sides attribute. We are able to define this method
in our abstract class because its implementation will not change in any of our
subclasses: all of our dice will produce a random number based on their number of
sides when rolled. It is important to understand, though, that this method cannot be
used in our abstract class, because there is no assigned value for the variable sides .
The subclasses which we create next are specific version of the abstract class
Die . That is, they are subclasses of Die for which a number of sides is specified
(six for Die_Six , ten for Die_Ten , and twenty for Die_Twenty ). Each class
contains just one method, a constructor which is used to create an instance of the
class in the form of an object. In each constructor method, the number of sides for
that specific die is assigned to the sides attribute, which is inherited from the
superclass (or abstraction) Die . In addition, each subclass of Die also inherits the
roll method. With this, we now have functioning die objects, which, when this
method is called, return a random number between 1 and the value of their
individual sides attribute.
2.5.2 Template
Closely related to the concept of an abstract class is the concept of templates. The
use of templates provides for the declaration of the structure and function of sub-
classes without regard for the data type to be handled by them. In other words, a
template is a sort of abstract class definition intended to be used on a data type that
is yet to be defined; a template for a class. The data type in question is declared only
upon the instantiation of an object from the template class, along with the actual
class definition. Before this point, in the template itself, a placeholder is used to
refer to the data type. Take a look at the following code segment for an example.
Search WWH ::




Custom Search