Java Reference
In-Depth Information
For example,
myCircle.radius
references the radius in
myCircle
, and
myCircle.getArea()
invokes the
getArea
method on
myCircle
. Methods are invoked
as operations on objects.
The data field
radius
is referred to as an
instance variable
, because it is dependent on a
specific instance. For the same reason, the method
getArea
is referred to as an
instance
method
, because you can invoke it only on a specific instance. The object on which an
instance method is invoked is called a
calling object
.
instance variable
instance method
calling object
Caution
Recall that you use
Math.methodName(arguments)
(e.g.,
Math.pow(3, 2.5)
)
to invoke a method in the
Math
class. Can you invoke
getArea()
using
Circle.getArea()
? The answer is no. All the methods in the
Math
class are static
methods, which are defined using the
static
keyword. However,
getArea()
is an
instance method, and thus nonstatic. It must be invoked from an object using
objectRefVar.methodName(arguments)
(e.g.,
myCircle.getArea()
). Fur-
ther explanation is given in Section 8.7, Static Variables, Constants, and Methods.
invoking methods
Note
Usually you create an object and assign it to a variable, and then later you can use the
variable to reference the object. Occasionally an object does not need to be referenced
later. In this case, you can create an object without explicitly assigning it to a variable
using the syntax:
new
Circle();
or
System.out.println(
"Area is "
+
new
Circle(
5
).getArea());
The former statement creates a
Circle
object. The latter creates a
Circle
object and
invokes its
getArea
method to return its area. An object created in this way is known
as an
anonymous object
.
anonymous object
8.5.3 Reference Data Fields and the
null
Value
The data fields can be of reference types. For example, the following
Student
class contains
a data field
name
of the
String
type.
String
is a predefined Java class.
reference data fields
class
Student {
String name;
// name has the default value null
int
age;
// age has the default value 0
boolean
isScienceMajor;
// isScienceMajor has default value false
char
gender;
// gender has default value '\u0000'
}
If a data field of a reference type does not reference any object, the data field holds a special
Java value,
null
.
null
is a literal just like
true
and
false
. While
true
and
false
are
Boolean literals,
null
is a literal for a reference type.
The default value of a data field is
null
for a reference type,
0
for a numeric type,
false
for a
boolean
type, and
\u0000
for a
char
type. However, Java assigns no default value to
a local variable inside a method. The following code displays the default values of the data
fields
name
,
age
,
isScienceMajor
, and
gender
for a
Student
object:
null
value
default field values
class
Test {
public static void
main(String[] args) {
Student student =
new
Student();
System.out.println(
"name? "
+
student.name
);