Java Reference
In-Depth Information
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 fol‐
lowed by the object's class (i.e., its type) and an optional argument list in parenthe‐
ses. These arguments are passed to the constructor for the class, which initializes
internal fields in the new object:
// Create a Point object representing (2,-3.5).
// Declare a variable p and store a reference to the new Point object
Point p = new Point ( 2.0 , - 3.5 );
// Create some other objects as well
// A Date object that represents the current time
Date d = new Date ();
// A HashSet object to hold a set of object
Set words = new HashSet ();
The new keyword is by far the most common way to create objects in Java. A few
other ways are also worth mentioning. First, classes that meet certain criteria 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 mech‐
anism that allows programs to load classes and create instances of those classes
dynamically. See Chapter 11 for more details. Finally, objects can also be created by
deserializing them. An object that has had its state saved, or serialized, usually to a
file, can be re-created using the java.io.ObjectInputStream class.
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 object
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
This syntax is very common when programming in object-oriented languages, and
Java is no exception, so you'll see it a lot. Note, in particular, p.distanceFromOri
gin() . This expression tells the Java compiler to look up a method named distance
FromOrigin() (which is 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 .
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.
Search WWH ::




Custom Search