Java Reference
In-Depth Information
3.1 Creating Objects
At the end of Chapter 1 we presented an overview of object-oriented concepts,
including the basic relationship between classes and objects. Then in Chapter 2, in
addition to discussing primitive data, we provided some examples of using objects
for the services they provide. This chapter explores these ideas further.
In previous examples, we've used the println method many times. As we men-
tioned in Chapter 2, the println method is a service provided by the System.out
object, which represents the standard output stream. To be more precise, the identi-
fier out is an object variable that is stored in the System class. It has been predefined
and set up for us as part of the Java standard class library. We can simply use it.
In Chapter 2 we also used the Scanner class, which represents an object that
allows us to read input from the keyboard or a file. We created a Scanner object
using the new operator. Once the object was created, we were able to use it for the
various services it provides. That is, we were able to invoke its methods.
Let's carefully examine the idea of creating an object. In Java, a variable name
represents either a primitive value or an object. Like variables that hold primitive
types, a variable that refers to an object must be declared. The class used to define
an object can be thought of as the type of an object. The declarations of object
variables have a similar structure to the declarations of primitive variables.
Consider the following two declarations:
int num;
String name;
The first declaration creates a variable that holds an integer value, as we've seen
many times before. The second declaration creates a String variable that holds
a reference to a String object. An object variable doesn't hold an object itself, it
holds the address of an object.
Initially, the two variables declared above don't contain any data. We say they
are uninitialized, which can be depicted as follows:
num
-
name
-
As we pointed out in Chapter 2, it is always important to make sure a variable
is initialized before using it. For an object variable, that means we must make sure
it refers to a valid object prior to using it. In most situations, the compiler will
issue an error if you attempt to use a variable before initializing it.
 
Search WWH ::




Custom Search