Java Reference
In-Depth Information
Notice
ColorChanger
contains the
main
method, so it can be executed as a Java
program. Figure 2.8 shows what the
ColorChanger
program looks like when it is executed.
FIGURE 2.8
The
ColorChanger
program.
Do not get hung up on the details of the graphical user interface (GUI)
code in the
ColorChanger
example. The SCJP exam no longer requires
knowledge of GUI programming. However, whether or not you understand
what the code does, you should definitely be able to identify the various
elements of the
ColorChanger
class.
All of these different elements of a class are listed in the exam objectives. If you have not
seen some of these concepts before, do not worry as I cover all of these topics in detail. We
start with a discussion on object initialization, which covers the details of constructors and
the instance and static initializers. Then we discuss the details of writing Java methods and
nested classes.
The Instantiation Process
Initialization is one of the main exam objectives and refers to the details of initializing
the various data types of Java. We have discussed the initialization of primitive types and
arrays. This section discusses the initialization of objects and the instantiation process.
As a Java programmer, you write classes and instantiate them to create objects. The
new
operator is the typical way to instantiate a class. For example, the following line of code
instantiates a new
java.text.DecimalFormat
object:
DecimalFormat df = new DecimalFormat(“#,###.00”);
This is a fairly straightforward statement, as you have seen the
new
operator countless
times before. The
new
operator instantiates the
DecimalFormat
object on the heap and
returns a reference to the object. The assignment operator = stores this reference in the
variable
df
. The
new
operator also has to specify which constructor is invoked on the class.
In the previous statement, a
String
is passed in, so the
DecimalFormat
constructor that
takes in a
String
is invoked.
Search WWH ::
Custom Search