Java Reference
In-Depth Information
Creating New Objects
When you write a Java program, you define a set of classes. As you learned during Day
1, “Getting Started with Java,” classes are templates used to create objects. These
objects, which are also called instances, are self-contained elements of a program with
related features and data. For the most part, you use the class merely to create instances
and then work with those instances. In this section, therefore, you learn how to create a
new object from any given class.
When using strings on Day 2, “The ABCs of Programming,” you learned that using a
string literal (a series of characters enclosed in double quotation marks) creates a new
instance of the class String with the value of that string.
The String class is unusual in that respect. Although it's a class, the use of a string lit-
eral serves as a shortcut to create instances of that class. To create instances of other
classes, the new operator is used.
NOTE
What about the literals for numbers and characters—don't they
create objects, too? Actually, they don't. The primitive data types
for numbers and characters create numbers and characters, but
for efficiency they actually aren't objects. On Day 5, “Creating
Classes and Methods,” you'll learn how to use objects to repre-
sent primitive values.
Using new
To create a new object, you use the new operator with the name of the class that should
be used as a template. The name of the class is followed by parentheses, as in these three
examples:
String name = new String();
URL address = new URL(“http://www.java21days.com”);
VolcanoRobot robbie = new VolcanoRobot();
The parentheses are important; don't leave them off. The parentheses can be empty, in
which case the most simple, basic object is created, or the parentheses can contain argu-
ments that determine the values of instance variables or other initial qualities of that
object.
The following examples show objects being created with arguments:
Random seed = new Random(6068430714);
Point pt = new Point(0, 0);
 
Search WWH ::




Custom Search