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 reader =
new BufferedReader(new FileReader(args));
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
calls its exists() method, and then discards it. The object is immedi-
ately discarded because it is never assigned to a variable:
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
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:
public int x, y;