Java Reference
In-Depth Information
So references in Java act in some ways like memory pointers but are much safer
with regard to creating program errors and security problems.
3.4.2 Accessing methods and fields
To create a useful program in Java, an object obviously needs to invoke methods
and to access data in other objects. This is done with a reference and the “. or
dot operator. For example, we invoke the calculate() method for an instance
of the Test class above as follows:
Test g1 = new Test (4, 5.1);
double z = g1.calculate ();
The invocation of calculate() with the g1 reference will cause the data for
the g1 object to be used with the bytecodes for that method.
Yo u can also directly access the data fields as in
double y = g1.x;
int j = g1.i;
In some situations you may not want one class to have access to certain data
(e.g. a password value) and methods. We will discuss access settings in Chapter 5
that allow you to determine what classes can access the fields and methods of a
class.
3.5 Static (or class) members
The Test class above has essentially no value outside of instantiations of the
class. In the course of program development a need often arises for utility methods
that might be needed for all instances of the class or for constants that are useful
to all instances of the class. Since object creation uses up memory resources it
is desirable to have access to such common resources without requiring them to
appear in each instance of the class.
However, we have seen that Java does everything within a class framework.
There are no global variables, for example, as in C
. Instead, Java has the
concept of class data and class methods that are defined in a class definition and
apply to all instances of the class. In fact, class data and class methods can be
accessed even without creating any instance of the class. Class data and methods
are also referred to as “static” members since the keyword static is used to
identify such members.
Static data are created when the class is loaded, even before any instantiation
of the class, and exists in just one place so that no matter how many instances of
that class are created, there remains only one copy of the static data. Instance data,
on the other hand, belongs solely to an instance of the class and new memory is
allocated for the data for each object.
/
C
++
Search WWH ::




Custom Search