Java Reference
In-Depth Information
In the EmployeeDemo program, two Employee objects are instantiated and
referenced using two Employee references: e1 and e2. Each of the fields is ini-
tialized in both objects using the dot operator. For example:
e1.name = “Robert Smith”;
e2.name = “Jane Smith”;
There are two Employee objects in memory, which means that there are two
fields called name, two fields called salary, two methods called computePay(),
and so on. How do you tell them apart? They are distinguished by which refer-
ence you use. The Employee reference e1 points to the Employee object whose
name is Robert Smith. The Employee reference e2 points to the Employee object
whose name is Jane Smith.
If you want to compute the pay of Robert Smith, you invoke computePay()
using e1:
e1.computePay();
If you want to mail a check to Jane Smith, you invoke mailCheck() using e2:
e2.mailCheck();
The references do more than keep the object from being garbage collected.
They represent your only access to the fields and methods of the object—using
a reference along with the dot operator.
The this Reference
Every object has a reference to itself represented by the this keyword. The this
reference is used in the methods of a class whenever a method accesses the
fields or other methods of the class.
For example, notice in the Employee class that the computePay() method
accesses the salary field, as follows:
public double computePay()
{
return salary/52;
}
The only way to access a field or method of an object is to have a reference
to the object. But in the computePay() method, we did not use a reference to
access salary. We simply used the salary variable, and everything worked fine.
The reason everything worked is that the compiler realizes that compute-
Pay() is accessing the salary field, so the compiler adds the reference for us.
Which reference does the compiler add? Well, computePay() needs a reference
Search WWH ::




Custom Search