384 APPENDIX A: Introduction to Java
Listing A-2. Creating the Object
ClassA var1 = new ClassA();
The process of creating objects involves declaring a reference variable to store the reference value of
the object and then creating the object using the new keyword followed by initializing the object by a
call to a constructor. The concept of constructor is explained later in the appendix. Listing A-3 splits
Listing A-2 to show the declaration and creation as separate steps.
Listing A-3. The Declaration and Creation in Separate Steps
- ClassA var1 ;
- var1 = new ClassA();
Line 1 declares the variable var1. The reference variable var1 can now be
used to manipulate the object whose reference value is stored in the reference
variable.
Line 2 creates the object using the new keyword and initialization by calling a
constructor ClassA().
Variables
In Java, variables store values of primitive data types and reference values of objects.
Listing A-4 illustrates variable declarations that can store primitive values.
Listing A-4. Variable Declarations
int a, b, c; // a, b and c are integer variables.
boolean flag; // flag is a boolean variable.
int i = 10, // i is an int variable with initial value 10
Variables that store reference values of objects are called reference variables. The reference variables
specify the type of reference that can be a class, an array, or an interface. Listing A-5 illustrates the
reference variable declaration.
Listing A-5. Reference Variable Declarations
ClassA var1 ; // Variable var1 can reference objects of class ClassA.
The declaration in the listing A-5 does not create any object of class ClassA; it just creates variable
that can store references of objects of ClassA.
Instance Members
Each object created (as illustrated in Listing A-2) has its own copies of the fields defined in its class.
The fields of an object are called instance variables. The values of the instance variables in an object
make up the object’s state. The methods of an object define its behavior. These methods are called