Classes and Objects Introduced
Now that we have introduced operators, expressions, statements, and methods, we can finally talk about classes. A class is a named collection of fields that hold data values and methods that operate on those values. Classes are just one of five reference types supported by Java, but they are the most important type. Classes are thoroughly documented in a chapter of their own, Chapter 3. We introduce them here, however, because they are the next higher level of syntax after methods, and because the rest of this chapter requires a basic familiarity with the concept of class and the basic syntax for defining a class, instantiating it, and using the resulting object.
The most important thing about classes is
that they define new data types. For example, you might define a
Point to represent a data point in the
two-dimensional Cartesian coordinate system. This class would define
fields (each of type
double) to hold the X and Y
coordinates of a point and methods to manipulate and operate on the
Point class is a new data type.
When discussing data types, it is
important to distinguish between the data type itself and the values
the data type represents.
char is a data type: it
represents Unicode characters. But a
represents a single specific character. A class is a data type; a
class value is called an object. We use the name
class because each class defines a type (or kind, or species, or
class) of objects. The
Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.