Java Reference
In-Depth Information
Notice that the remaining fractional value 34567890 was rounded up to 4.
7.
Change the value of doubleTest to 12345678901234567890.
Notice that now there is an “out of range” error and that there is a huge difference regarding how the JVM handles
a value that is too big versus a value that is too precise. (These are the kind of differences that drive new programmers
crazy, so hang in there!)
8.
Undo the change.
Let's drive the point home.
9.
Uncomment the statement that creates the reference variable ef and add the following
statement immediately after:
System.out.println("The value of ef is " + ef);
What do you think the result will be?
10.
Run EmployeeApp and close the Employee Information frame.
The console should display something like the following:
The value of ef is c5.EmployeeFrame[frame0,350,200,400x450, invalid,title=Employee
Information,resizable,normal]
Are you surprised by the results? You probably thought that a storage location would be displayed (because ef is a
reference variable and that is what happened when you tried to display emp).
When println is used to display a reference variable, the JVM actually calls a method named toString within the
referenced object. An Employee object's (emp's) toString method returns the object's storage location. However,
not all JRE classes' toString methods do that. Some JRE classes' toString methods return different information. For
instance, the Frame class's toString method returns properties such as the size, location, and title (that the JVM then
displays as in step 10). “Why does this happen?” you ask? The answer is inheritance.
To help explain inheritance, let's explore the toString method further.
The toString Method
To reiterate: when a reference variable is displayed with the println statement, the JVM searches for the reference
variable's assigned object's toString method. The toString method returns values to the JVM that are then displayed.
Now, the Great-Grandpappy of all classes, Object , has a toString method. This method specifies that the variable type
will be displayed, followed by the “at sign” (@), and then the storage location. We have proven that this is what occurs
(for example, with the Employee reference variable emp). However, the Object class documentation suggests that the
toString method should be overridden by all subclasses.
The Component class (of which the Frame class is a subclass) does override the toString method. The Component
class' toString method specifies that a Component object's size, title, and so on should be displayed, not the hash code.
In other words, all Component subclasses that do not override the toString method will display this information.
 
Search WWH ::




Custom Search