Java Reference
In-Depth Information
Chapter 5
Variables
In this chapter, we will introduce primitive variables and compare/contrast them to reference variables. We will
demonstrate how to perform math and logic functions using both primitive and String variables. A new GUI
component, text field (which enables a user to input information to an application), will be demonstrated and we will
revisit inheritance in more detail.
At the end of this chapter, you should understand:
Primitive versus reference variables
How to convert between variable types
Wrapper classes
Text fields
Inheritance
After completing the chapter, you should be able to:
Use text fields to retrieve and display information
Perform calculations
Convert between numeric and string information
Override inherited methods
Reference versus Primitive Variables
We have hidden the full explanation of reference variables from you as long as possible. Reference variables are
necessarily complex and, unfortunately, you cannot continue without understanding them.
All of the variables we have used have been reference variables and, often, we have talked about the variable and
the object (assigned to the variable) as if they were the same thing. In actuality, they are two different entities.
For example, we have said, “have the program pass an Employee object” or “have the method accept on Employee
object” when, in actuality, an Employee variable is being passed or accepted.
When a reference variable, such as emp in EmployeeApp, is created, a small, fixed amount of space is reserved
in the computer's main memory. However, when an object is created (i.e., an Employee object is instantiated), a copy
of the entire class is moved into main memory. When the object is assigned to the reference variable, the storage
location (address in main memory) of the object is moved into the reference variable.
Let's try a diagram. When you run EmployeeApp, the class's main method is loaded into the computer's main
memory and the main method statements are executed. When the variable emp is created ( Employee emp; ), main
memory space is allocated for that variable but the space is empty (see Figure 5-1 ).
 
Search WWH ::




Custom Search