Java Reference
In-Depth Information
Here are the main components of a class that we'll see in the sections that follow:
•
Fields (the data stored in each object)
•
Methods (the behavior each object can execute)
•
Constructors (code that initializes an object as it is being constructed with the
new
keyword)
•
Encapsulation (protects an object's data from outside access)
We'll focus on these concepts by creating several major versions of the
Point
class.
The first version will give us
Point
objects that contain only data. The second version
will add behavior to the objects. The third version will allow us to construct
Point
s at
any initial position. The finished code will encapsulate each
Point
object's internal
data to protect it from unwanted outside access. The early versions of the class will be
incomplete and will be used to illustrate each feature of a class in isolation. Only the
finished version of the
Point
class will be written in proper object-oriented style.
The first version of our
Point
class will contain state only. To specify each object's
state, we declare special variables inside the class called
fields.
There are many syn-
onyms for “field” that come from other programming languages and environments,
such as “instance variable,” “data member,” and “attribute.”
Field
A variable inside an object that makes up part of its internal state.
The syntax for declaring a field is the same as the syntax for declaring normal vari-
ables: a type followed by a name and a semicolon. But unlike normal variables, fields
are declared directly inside the
{
and
}
braces of your class. When we declare a field,
we're saying that we want every object of this class to have that variable inside it.
In previous chapters we've seen that every class should be placed into its own file.
The following code, written in the file
Point.java
, defines the first version of our
Point
class:
1 // A Point object represents a pair of (x, y) coordinates.
2 // First version: state only.
3
4
public class
Point {
5
int
x;
6
int
y;
7 }
This code specifies that each
Point
object will contain two fields (an integer
called
x
and an integer called
y
). It may look as though the code declares a pair of
Search WWH ::
Custom Search