2.7. 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
class named 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. 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 char value
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 Point class is a data type
that represents X,Y points, while a Point object
represents a single specific X,Y point. As you might imagine, classes
and their objects are closely linked. In the sections that follow, we
will discuss both.
2.7.1. Defining a Class
Here is a possible
definition of the Point class we have been
discussing:
/** Represents a Cartesian (x,y) point */This class definition is stored in a file named
public class Point {
public double x, y; // The coordinates of the point
public Point(double x, double y) { // A constructor that
this.x = x; this.y = y; // initializes the fields
}
public double distanceFromOrigin( ) { // A method that operates on
return Math.sqrt(x*x + y*y); // the x and y fields
}
}
Point.java and compiled to a file named
Point.class , where it is available for use by
Java programs and other classes. This class definition is provided
here for completeness and to provide context, but
don't expect to understand all the details just yet;
most of Chapter 3 is devoted to the topic of
defining classes.Keep in mind that you don't have to define every
class you want to use in a Java program. The Java platform includes
thousands of predefined classes that are guaranteed to be available
on every computer that runs Java.
2.7.2. Creating an Object
Now
that we have defined the Point class as a new data
type, we can use the following line to declare a variable that holds
a Point object:
Point p;Declaring a variable to hold a
Point object does not create the object itself,
however. To actually create an object, you must use the
new operator. This
keyword is followed by the object's class (i.e., its
type) and an optional argument list in parentheses. These arguments
are passed to the constructor method for the class, which initializes
internal fields in the new object:
// Create a Point object representing (2,-3.5).The new keyword
// Declare a variable p and store a reference to the new Point object in it.
Point p = new Point(2.0, -3.5);
// Create some other objects as well
Date d = new Date( ); // A Date object that represents the current time
Set words = new HashSet( ); // A HashSet object to hold a set of objects
is by far the most common way to create objects in Java. A few other
ways are also worth mentioning. First, a couple of classes are so
important that Java defines special literal syntax for creating
objects of those types (as we discuss later in this section). Second,
Java supports a dynamic loading mechanism that allows programs to
load classes and create instances of those classes dynamically. This
dynamic instantiation is done with the newInstance(
) methods of java.lang.Class and
java.lang.reflect.Constructor. Finally, objects
can also be created by deserializing them. In other words, an object
that has had its state saved, or serialized, usually to a file, can
be recreated using the java.io.ObjectInputStream
class.
2.7.3. Using an Object
Now
that we've seen how to define classes and
instantiate them by creating objects, we need to look at the Java
syntax that allows us to use those objects. Recall that a class
defines a collection of fields and methods. Each object has its own
copies of those fields and has access to those methods. We use the
dot character (.)
to access the named fields and methods of an object. For example:
Point p = new Point(2, 3); // Create an objectThis syntax is central to object-oriented programming in Java, so
double x = p.x; // Read a field of the object
p.y = p.x * p.x; // Set the value of a field
double d = p.distanceFromOrigin( ); // Access a method of the object
you'll see it a lot. Note, in particular, the
expression p.distanceFromOrigin( ). This tells the
Java compiler to look up a method named distanceFromOrigin(
) defined by the class Point and use
that method to perform a computation on the fields of the object
p. We'll cover the details of
this operation in Chapter 3.
2.7.4. Object Literals
In
our discussion of primitive types, we saw that each primitive type
has a literal syntax for including values of the type literally into
the text of a program. Java also defines a literal syntax for a few
special reference types, as described next.
2.7.4.1 String literals
The
String class
represents text as a string of characters. Since programs usually
communicate with their users through the written word, the ability to
manipulate strings of text is quite important in any programming
language. In some languages, strings are a primitive type, on a par
with integers and characters. In Java, however, strings are objects;
the data type used to represent text is the String
class.
Because strings are such a
fundamental data type, Java allows you to include text literally in
programs by placing it between double-quote (")
characters. For example:
String name = "David";Don't confuse the double-quote characters that
System.out.println("Hello, " + name);
surround string literals with the single-quote (or apostrophe)
characters that surround char
literals. String literals can contain any of the escape sequences
char literals can (see Table 2-2). Escape sequences are particularly useful for
embedding double-quote characters within double-quoted string
literals. For example:
String story = "\t\"How can you stand it?\" he asked sarcastically.\n";String literals cannot contain
comments and may consist of only a single line. Java does not support
any kind of continuation-character syntax that allows two separate
lines to be treated as a single line. If you need to represent a long
string of text that does not fit on a single line, break it into
independent string literals and use the + operator
to concatenate the literals. For example:
String s = "This is a test of the // This is illegal; string literalsThis concatenation of literals is done when your program is compiled,
emergency broadcast system"; // cannot be broken across lines.
String s = "This is a test of the " + // Do this instead
"emergency broadcast system";
not when it is run, so you do not need to worry about any kind of
performance penalty.
2.7.4.2 Type literals
The
second type that supports its own
special object literal syntax is the class named
Class. Instances of the Class
class represent a Java data type. To include a
Class object literally in a Java program, follow
the name of any data type with .class. For
example:
Class typeInt = int.class;
Class typeIntArray = int[].class;
Class typePoint = Point.class;
2.7.4.3 The null reference
The null
keyword
is a special literal value that is a reference to nothing, or an
absence of a reference. The null value is unique
because it is a member of every reference type. You can assign
null to variables of any reference type. For
example:
String s = null;
Point p = null;