img
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a class are
called members of the class. In most classes, the instance variables are acted upon and accessed
by the methods defined for that class. Thus, as a general rule, it is the methods that determine
how a class' data can be used.
Variables defined within a class are called instance variables because each instance of the
class (that is, each object of the class) contains its own copy of these variables. Thus, the data
for one object is separate and unique from the data for another. We will come back to this point
shortly, but it is an important concept to learn early.
All methods have the same general form as main( ), which we have been using thus far.
However, most methods will not be specified as static or public. Notice that the general form
of a class does not specify a main( ) method. Java classes do not need to have a main( ) method.
You only specify one if that class is the starting point for your program. Further, applets don't
require a main( ) method at all.
NOTE  C++ programmers will notice that the class declaration and the implementation of the
OTE
methods are stored in the same place and not defined separately. This sometimes makes for very
large .java files, since any class must be entirely defined in a single source file. This design feature
was built into Java because it was felt that in the long run, having specification, declaration, and
implementation all in one place makes for code that is easier to maintain.
A Simple Class
Let's begin our study of the class with a simple example. Here is a class called Box that defines
three instance variables: width, height, and depth. Currently, Box does not contain any
methods (but some will be added soon).
class Box {
double width;
double height;
double depth;
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home