Java Reference
In-Depth Information
A: No. The object does not change, just the data type of the reference
to it. This is an important point to understand. If I instantiate a
Salary object, I get a Salary object, no matter what data type its ref-
erence is.
Q: So why not always use a parent class reference if it doesn't change
anything?
A: Well, be careful. I said the object does not change, but how it is
viewed does change. If I use an Employee reference to a Salary
object, the object does not lose any data, but I lose the ability to
access those fields and methods from the Salary class using the
parent class reference.
Q: You can never access them? Then you have lost something.
A: No, you can still access them, but you have to cast the Employee
reference to a Salary reference. Let's discuss the casting process
first. I will then show you examples where using a parent class ref-
erence to a child object is advantageous.
Casting References
We saw in Chapter 2, “Java Fundamentals,” that the cast operator can be used
to cast primitive data types. For example, suppose that you have a double that
you want to store in a float. Even if the double fits easily in the float, the com-
piler still requires you to use the cast operator:
double pi = 3.14159;
float a = pi; //Does not compile!
float b = (float) pi; //Works fine
You might think the compiler should be smart enough to realize that 3.14159
fits into a float, so no casting is necessary; however, it is important to realize
that the compiler only knows data types. When you assign a 64-bit double to a
32-bit float, the compiler only sees a larger piece of data being stored in a
smaller piece. Because data could be lost, the cast operator tells the compiler
you know what you are doing, and any loss of data is acceptable.
By the way, casting a float to a double is acceptable because they are
compatible data types. You cannot cast a String to a float, a boolean to
an int, an Employee to a char, and so on, because these data types are
not compatible.
Search WWH ::




Custom Search