Chapter 5. Objects and References
Until now we have seen about the variables and
types of variables in Java. Normally we give the variable name in its
declaration with the type which is going to store.
Employee emp;
In the above declaration emp is the reference
variable name and the type of the emp is Employee. But the declaring the reference
variable does not create any object. That means it does not allocate memory
until you instantiate the class. So how you can create an object? First you
need to instantiate the class. This can be done using the “new” operator.
Following line shows the instantiation with the constructor of class.
new Employee()
What is the value of new Employee(). When this
expression is evaluated, it results in creation of object and the value of the
expression is reference to the object. What is the difference between an object
and reference to object. If you want to invite your friend to your house, how
do you refer your house? You need to tell him the address of your house. In
this case house is an object and address of the house is reference to object.
Now you have declared a variable called emp and
instatiate the employee class. So how you are going to interrelate it? For that
you need to assign the value to reference variable.
Employee Emp;
Emp = new Employee();
To assign the value, you need to use assignment
operator (=).
What happens in memory when you are creating
reference. When you declare the reference variable, it does not allocate
memory. When you instantiate and assign, the memory will be allocated to the
object.