Java Reference
In-Depth Information
1.7. Classes and Objects
The Java programming language, like many object-oriented program-
ming languages, provides a tool to solve programming problems using
the notions of classes and objects. Every object has a class that defines
its data and behavior. Each class has three kinds of members:
•
Fields are data variables associated with a class and its objects.
Fields store results of computations performed by the class.
•
Methods contain the executable code of a class. Methods are built
from statements. The way in which methods are invoked, and the
statements contained within those methods, are what ultimately
directs program execution.
•
Classes and interfaces can be members of other classes or inter-
faces (you will learn about interfaces soon).
Here is the declaration of a simple class that might represent a point on
a two-dimensional plane:
class Point {
public double x, y;
}
This
Point
class has two fields representing the
x
and
y
coordinates of a
point and has (as yet) no methods. A class declaration like this one is,
conceptually, a plan that defines what objects manufactured from that
class look like, plus sets of instructions that define the behavior of those
objects.
Members of a class can have various levels of
visibility
or
accessibility.
The
public
declaration of
x
and
y
in the
Point
class means that any code
with access to a
Point
object can read and modify those fields. Other
levels of accessibility limit member access to code in the class itself or to
other related classes.