Java Reference
In-Depth Information
type. For example, Java does not offer a complex number primitive type. A
programmer, however, can create a complex number type with a class definition.
The definition would include data - two floating-point values for the real and
imaginary parts of the complex number - and operations performed with that
data. That is, the addition, multiplication, conjugation, and other operations for
complex numbers would be defined by the methods of the class definition.
We see that the class definition uses primitives to hold the data and that the
operations are written at the source code level; you do not define new machine
level (or virtual machine level in the case of Java) instructions for the class. The
principle, however, is the same. The class definition creates a new custom data
type with its own operational capabilities.
With the primitives you create instances of a type with a declaration such as
float x = 5.0f;
This allocates 4 bytes of memory to hold the value 5.0 in memory and the data is
labeled as belonging to the floating-point type so that only legal float operations
can act upon it.
Similarly, once a class definition is available, instances of the class can be
created. This means that memory is allocated for all the data fields in the definition.
(The code for the operations defined in the class is not duplicated with each
instance since Java knows how to find the code when needed.) A special method
called the constructor initializes the data values when the instance is created.
Just as you can create multiple variables to hold float values, you can create
multiple instances of a class such as the complex number class. Such instances
of the class are called objects .
With object-oriented programming, we go beyond just thinking in terms of
data-type representation and operations and instead look at using classes to rep-
resent any sort of self-contained entity. In a physics code we might, for example,
define a class that represents a particle. The data would include fields for the
name, mass, charge, and other qualities that define a particle. The methods would
implement the particle's behavior such as its response to electric and gravitational
fields and its interactions with other particles.
3.3 Class definition
In Chapter 1 we presented class definitions of very simple classes in the code
for HelloWorld.java and HelloWorldApp.java .With only init() and
paint() methods in the former and the main() method in the latter, the capa-
bilities of those classes were very limited. A class typically contains:
Data fields - Declare the data values belonging to the class or object.
Methods - Functions to carry out tasks for the objects.
Search WWH ::




Custom Search