// ...
}
Creating Objects
Every object in Java is allocated on the heap. To create objects in Java, you
use the new operator.
1. The following example creates a
BufferedReader object:
BufferedReader reader =
new BufferedReader(new FileReader(args[0]));
2. Objects are typically assigned to variables, but they need not be. It is
also very common to create anonymous objects that are used and dis-
carded in one sequence. The following example creates a
File object,
calls its exists() method, and then discards it. The object is immedi-
ately discarded because it is never assigned to a variable:
if(new File(args[1]).exists())
System.err.println(“Error: output file already exists!”);
You don’t have to explicitly destroy objects in Java. When an object is no
longer in use, it is automatically reclaimed by the garbage collector.
Accessing Fields and Methods
A class contains fields or data variables that are attached to objects. It also
contains methods with the executable code of the class.
To access a field or a method of an object, you separate its name from the
object reference with a dot, as in
writer.close();
Static
By default, the variables or methods declared in a class are attached to
objects of that class. However, it is possible to declare variables or methods
attached to the class.
1. The following example declares a class with two fields:
x and y. Every
Point object has the two fields:
class Point
{
public int x, y;
}
466
Appendix A
EXAMPLE
EXAMPLE
EXAMPLE
EXAMPLE

Get XML by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.