epubjs
Version:
Render ePub documents in the browser, across many devices
391 lines (388 loc) • 53.1 kB
HTML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>HelloJava</title><link rel="stylesheet" href="core.css" type="text/css"/><meta name="generator" content="DocBook XSL Stylesheets V1.74.0"/></head><body><div class="sect1" title="HelloJava"><div class="titlepage"><div><div><h1 class="title"><a id="learnjava3-CHP-2-SECT-2"/>HelloJava</h1></div></div></div><p>In the tradition of introductory programming texts, we will begin
with Java’s equivalent of the archetypal “Hello World” application,
<code class="literal">HelloJava</code>.</p><p>We’ll end up taking four passes at this example before we’re done
(<code class="literal">HelloJava</code>, <code class="literal">HelloJava2</code>, etc.), adding features and
introducing new concepts along the way. But let’s start with the
minimalist version:</p><a id="I_2_tt11"/><pre class="programlisting"> <code class="kd">public</code> <code class="kd">class</code> <code class="nc">HelloJava</code> <code class="o">{</code>
<code class="kd">public</code> <code class="kd">static</code> <code class="kt">void</code> <code class="nf">main</code><code class="o">(</code> <code class="n">String</code><code class="o">[]</code> <code class="n">args</code> <code class="o">)</code> <code class="o">{</code>
<code class="n">System</code><code class="o">.</code><code class="na">out</code><code class="o">.</code><code class="na">println</code><code class="o">(</code><code class="s">"Hello, Java!"</code><code class="o">);</code>
<code class="o">}</code>
<code class="o">}</code></pre><p>This five-line program declares a class called <code class="literal">HelloJava</code> and a method called <code class="literal">main()</code> . It uses a predefined method called
<a id="I_indexterm2_id636345" class="indexterm"/><code class="literal">println()</code> to write some
text as output. This is a <span class="emphasis"><em>command-line program</em></span>, which
means that it runs in a shell or DOS window and prints its output there.
That’s a bit old-school for our taste, so before we go any further, we’re
going to give <code class="literal">HelloJava</code> a
<span class="emphasis"><em>graphical user interface</em></span> (GUI). Don’t worry about the
code yet; just follow along with the progression here, and we’ll come back
for explanations in a moment.</p><p>In place of the line containing the <a id="I_indexterm2_id636377" class="indexterm"/><code class="literal">println()</code> method, we’re
going to use a <a id="I_indexterm2_id636389" class="indexterm"/><code class="literal">JFrame</code> object to put a
window on the screen. We can start by replacing the <code class="literal">println</code> line with the following three
lines:</p><a id="I_2_tt12"/><pre class="programlisting"> <code class="n">JFrame</code> <code class="n">frame</code> <code class="o">=</code> <code class="k">new</code> <code class="n">JFrame</code><code class="o">(</code> <code class="s">"Hello, Java!"</code> <code class="o">);</code>
<code class="n">frame</code><code class="o">.</code><code class="na">setSize</code><code class="o">(</code> <code class="mi">300</code><code class="o">,</code> <code class="mi">300</code> <code class="o">);</code>
<code class="n">frame</code><code class="o">.</code><code class="na">setVisible</code><code class="o">(</code> <code class="kc">true</code> <code class="o">);</code></pre><p>This snippet creates a <code class="literal">JFrame</code>
object with the title “Hello, Java!” The <code class="literal">JFrame</code> is a graphical window. To display it, we
simply configure its size on the screen using the <a id="I_indexterm2_id636429" class="indexterm"/><code class="literal">setSize()</code> method and make
it visible by calling the <a id="I_indexterm2_id636441" class="indexterm"/><code class="literal">setVisible()</code>
method.</p><p>If we stopped here, we would see an empty window on the screen with
our “Hello, Java!” banner as its title. We’d like our message inside the
window, not just scrawled at the top of it. To put something in the
window, we need a couple more lines. The following complete example adds a
<a id="I_indexterm2_id636459" class="indexterm"/><code class="literal">JLabel</code> object to display
the text centered in our window. The additional <a id="I_indexterm2_id636469" class="indexterm"/><code class="literal">import</code> line at the top is
necessary to tell Java where to find the <code class="literal">JFrame</code> and <code class="literal">JLabel</code> classes (the definitions of the <code class="literal">JFrame</code> and <code class="literal">JLabel</code> objects that we’re using).</p><a id="I_2_tt13"/><pre class="programlisting"> <code class="kn">import</code> <code class="nn">javax.swing.*</code><code class="o">;</code>
<code class="kd">public</code> <code class="kd">class</code> <code class="nc">HelloJava</code> <code class="o">{</code>
<code class="kd">public</code> <code class="kd">static</code> <code class="kt">void</code> <code class="nf">main</code><code class="o">(</code> <code class="n">String</code><code class="o">[]</code> <code class="n">args</code> <code class="o">)</code> <code class="o">{</code>
<code class="n">JFrame</code> <code class="n">frame</code> <code class="o">=</code> <code class="k">new</code> <code class="n">JFrame</code><code class="o">(</code> <code class="s">"Hello, Java!"</code> <code class="o">);</code>
<code class="n">JLabel</code> <code class="n">label</code> <code class="o">=</code> <code class="k">new</code> <code class="n">JLabel</code><code class="o">(</code><code class="s">"Hello, Java!"</code><code class="o">,</code> <code class="n">JLabel</code><code class="o">.</code><code class="na">CENTER</code> <code class="o">);</code>
<code class="n">frame</code><code class="o">.</code><code class="na">add</code><code class="o">(</code><code class="n">label</code><code class="o">);</code>
<code class="n">frame</code><code class="o">.</code><code class="na">setSize</code><code class="o">(</code> <code class="mi">300</code><code class="o">,</code> <code class="mi">300</code> <code class="o">);</code>
<code class="n">frame</code><code class="o">.</code><code class="na">setVisible</code><code class="o">(</code> <code class="kc">true</code> <code class="o">);</code>
<code class="o">}</code>
<code class="o">}</code></pre><p>Now to compile and run this source, select the
<span class="emphasis"><em>ch02/HelloJava.java</em></span> class from the package explorer
along the left and click the <span class="emphasis"><em>Run</em></span> button in the
toolbar along the top. The <span class="emphasis"><em>Run</em></span> button is a green
circle with a white arrow pointing to the right. See <a class="xref" href="ch02s03.html#learnjava4-CHP-2-FIG-4" title="Figure 2-4. Running the HelloJava application">Figure 2-4</a>.</p><div class="figure"><a id="learnjava4-CHP-2-FIG-4"/><div class="figure-contents"><div class="mediaobject"><a id="I_2_tt16_4"/><img src="httpatomoreillycomsourceoreillyimages1707602.png.jpg" alt="Running the HelloJava application"/></div></div><p class="title">Figure 2-4. Running the HelloJava application</p></div><p>You should see the proclamation shown in <a class="xref" href="ch02s03.html#learnjava3-CHP-2-FIG-1" title="Figure 2-5. The output of the HelloJava application">Figure 2-5</a>. Congratulations, you have run your
first Java application! Take a moment to bask in the glow of your
monitor.</p><div class="figure"><a id="learnjava3-CHP-2-FIG-1"/><div class="figure-contents"><div class="mediaobject"><a id="I_2_tt16_5"/><img src="httpatomoreillycomsourceoreillyimages1707603.png" alt="The output of the HelloJava application"/></div></div><p class="title">Figure 2-5. The output of the HelloJava application</p></div><p>Be aware that when you click on the window’s close box, the window
goes away, but your program is still running. (We’ll fix this shutdown
behavior in a later version of the example.) To stop the Java application
in Eclipse, click the big red button in the console window. If you are
running the example on the command line, type Ctrl-C. Note that nothing
stops you from running more than one instance (copy) of the application at
a time.</p><p><code class="literal">HelloJava</code> may be a small program,
but there is quite a bit going on behind the scenes. Those few lines
represent the tip of an iceberg. What lies under the surface are the
layers of functionality provided by the Java language and its foundation
class libraries. Remember that in this chapter, we’re going to cover a lot
of ground quickly in an effort to show you the big picture. We’ll try to
offer enough detail for a good understanding of what is happening in each
example, but will defer detailed explanations until the appropriate
chapters. This holds for both elements of the Java language and the
object-oriented concepts that apply to them. With that said, let’s take a
look now at what’s going on in our first example.</p><div class="sect2" title="Classes"><div class="titlepage"><div><div><h2 class="title"><a id="learnjava3-CHP-2-SECT-2.1"/>Classes</h2></div></div></div><p>The first example defines a class named <code class="literal">HelloJava</code>.</p><a id="I_2_tt17"/><pre class="programlisting"> <code class="kd">public</code> <code class="kd">class</code> <code class="nc">HelloJava</code> <code class="o">{</code>
<code class="o">...</code></pre><p>Classes are the fundamental building blocks of most
object-oriented languages. A <a id="I_indexterm2_id636631" class="indexterm"/><span class="emphasis"><em>class</em></span> is a group of data items with
associated functions that can perform operations on that data. The data
items in a class are called <a id="I_indexterm2_id636643" class="indexterm"/><span class="emphasis"><em>variables</em></span>, or sometimes <a id="I_indexterm2_id636654" class="indexterm"/><span class="emphasis"><em>fields</em></span>; in Java, functions are called
<a id="I_indexterm2_id636662" class="indexterm"/><span class="emphasis"><em>methods</em></span>. The primary benefits of an
object-oriented language are this association between data and
functionality in class units and also the ability of classes to
<a id="I_indexterm2_id636674" class="indexterm"/><span class="emphasis"><em>encapsulate</em></span> or hide details, freeing
the developer from worrying about low-level details.</p><p>In an application, a class might represent something concrete,
such as a button on a screen or the information in a spreadsheet, or it
could be something more abstract, such as a sorting algorithm or perhaps
the sense of ennui in a video game character. A class representing a
spreadsheet might, for example, have variables that represent the values
of its individual cells and methods that perform operations on those
cells, such as “clear a row” or “compute values.”</p><p>Our <code class="literal">HelloJava</code> class is an
entire Java application in a single class. It defines just one method,
<code class="literal">main()</code> , which holds the body of our
program:</p><a id="I_2_tt18"/><pre class="programlisting"> <code class="kd">public</code> <code class="kd">class</code> <code class="nc">HelloJava</code> <code class="o">{</code>
<code class="kd">public</code> <code class="kd">static</code> <code class="kt">void</code> <code class="nf">main</code><code class="o">(</code> <code class="n">String</code><code class="o">[]</code> <code class="n">args</code> <code class="o">)</code> <code class="o">{</code>
<code class="o">...</code></pre><p>It is this <code class="literal">main()</code> method that
is called first when the application is started. The bit labeled
<code class="literal">String [] args</code> allows us to pass
<span class="emphasis"><em>command-line arguments</em></span> to the application. We’ll
walk through the <code class="literal">main()</code> method in the
next section. Finally, we’ll note that although this version of <code class="literal">HelloJava</code> does not define any variables as
part of its class, it does use two variables, <code class="literal">frame</code> and <code class="literal">label</code>, inside its <code class="literal">main()</code> method. We’ll have more to say about
variables soon as well.</p></div><div class="sect2" title="The main() Method"><div class="titlepage"><div><div><h2 class="title"><a id="learnjava3-CHP-2-SECT-2.2"/>The main() Method</h2></div></div></div><p><a id="idx10080" class="indexterm"/> <a id="idx10097" class="indexterm"/> <a id="idx10099" class="indexterm"/>As we saw when we ran our example, running a Java
application means picking a particular class and passing its name as an
argument to the Java virtual machine. When we did this, the <code class="literal">java</code> command looked in our <code class="literal">HelloJava</code> class to see if it contained the
special method named <code class="literal">main()</code> of just
the right form. It did, and so it was executed. If it had not been
there, we would have received an error message. The <code class="literal">main()</code> method is the entry point for
applications. Every standalone Java application includes at least one
class with a <code class="literal">main()</code> method that
performs the necessary actions to start the rest of the program.</p><p>Our <code class="literal">main()</code> method sets up a
window (a <code class="literal">JFrame</code>) to hold the visual
output of the <code class="literal">HelloJava</code> class. Right
now, it’s doing all the work in the application. But in an
object-oriented application, we normally delegate responsibilities to
many different classes. In the next incarnation of our example, we’re
going to perform just such a split—creating a second class—and we’ll see
that as the example subsequently evolves, the <code class="literal">main()</code> method remains more or less the same,
simply holding the startup procedure.</p><p>Let’s quickly walk through our <code class="literal">main()</code> method, just so we know what it does.
First, <code class="literal">main()</code> creates a <code class="literal">JFrame</code>, the window that will hold our
example:</p><a id="I_2_tt19"/><pre class="programlisting"> <code class="n">JFrame</code> <code class="n">frame</code> <code class="o">=</code> <code class="k">new</code> <code class="n">JFrame</code><code class="o">(</code><code class="s">"Hello, Java!"</code><code class="o">);</code></pre><p>The word <a id="I_indexterm2_id636907" class="indexterm"/><code class="literal">new</code> in this line of
code is very important. <code class="literal">JFrame</code> is the
name of a class that represents a window on the screen, but the class
itself is just a template, like a building plan. The <code class="literal">new</code> keyword tells Java to allocate memory and
actually create a particular <a id="I_indexterm2_id636930" class="indexterm"/><code class="literal">JFrame</code> object. In this
case, the argument inside the parentheses tells the <code class="literal">JFrame</code> what to display in its title bar. We
could have left out the “Hello, Java” text and used empty parentheses to
create a <code class="literal">JFrame</code> with no title, but
only because the <code class="literal">JFrame</code> specifically
allows us to do that.</p><p>When frame windows are first created, they are very small. Before
we show the <code class="literal">JFrame</code>, we set its size
to something reasonable:</p><a id="I_2_tt20"/><pre class="programlisting"> <code class="n">frame</code><code class="o">.</code><code class="na">setSize</code><code class="o">(</code> <code class="mi">300</code><code class="o">,</code> <code class="mi">300</code> <code class="o">);</code></pre><p>This is an example of invoking a method on a particular object. In
this case, the <a id="I_indexterm2_id636981" class="indexterm"/><code class="literal">setSize()</code> method is
defined by the <code class="literal">JFrame</code> class, and it
affects the particular <code class="literal">JFrame</code> object
we’ve placed in the variable <code class="literal">frame</code>.
Like the frame, we also create an instance of <code class="literal">JLabel</code> to hold our text inside the
window:</p><a id="I_2_tt21"/><pre class="programlisting"> <code class="n">JLabel</code> <code class="n">label</code> <code class="o">=</code> <code class="k">new</code> <code class="n">JLabel</code><code class="o">(</code><code class="s">"Hello, Java!"</code><code class="o">,</code> <code class="n">JLabel</code><code class="o">.</code><code class="na">CENTER</code> <code class="o">);</code></pre><p><code class="literal">JLabel</code> is much like a physical
label. It holds some text at a particular position—in this case, on our
frame. This is a very object-oriented concept: using an object to hold
some text, instead of simply invoking a method to “draw” the text and
moving on. The rationale for this will become clearer later.</p><p>Next, we have to place the label into the frame we created:</p><a id="I_2_tt22"/><pre class="programlisting"> <code class="n">frame</code><code class="o">.</code><code class="na">add</code><code class="o">(</code> <code class="n">label</code> <code class="o">);</code></pre><p>Here, we’re calling a method named <code class="literal">add()</code>to place our label inside the <code class="literal">JFrame</code>. The <code class="literal">JFrame</code> is a kind of container that can hold
things. We’ll talk more about that later. <code class="literal">main()</code>’s final task is to show the frame
window and its contents, which otherwise would be invisible. An
invisible window makes for a pretty boring application.</p><a id="I_2_tt23"/><pre class="programlisting"> <code class="n">frame</code><code class="o">.</code><code class="na">setVisible</code><code class="o">(</code> <code class="kc">true</code> <code class="o">);</code></pre><p>That’s the whole <code class="literal">main()</code> method.
As we progress through the examples in this chapter, it will remain
mostly unchanged as the <code class="literal">HelloJava</code>
class evolves around it.<a id="I_indexterm2_id637096" class="indexterm"/><a id="I_indexterm2_id637103" class="indexterm"/><a id="I_indexterm2_id637110" class="indexterm"/></p></div><div class="sect2" title="Classes and Objects"><div class="titlepage"><div><div><h2 class="title"><a id="learnjava3-CHP-2-SECT-2.3"/>Classes and Objects</h2></div></div></div><p><a id="I_indexterm2_id637124" class="indexterm"/> <a id="I_indexterm2_id637133" class="indexterm"/>A class is a blueprint for a part of an application; it
holds methods and variables that make up that component. Many individual
working copies of a given class can exist while an application is
active. These individual incarnations are called <a id="I_indexterm2_id637146" class="indexterm"/><span class="emphasis"><em>instances</em></span> of the class, or <a id="I_indexterm2_id637155" class="indexterm"/><span class="emphasis"><em>objects</em></span>. Two instances of a given
class may contain different data, but they always have the same
methods.</p><p>As an example, consider a <code class="literal">Button</code> class. There is only one <code class="literal">Button</code> class, but an application can create
many different <code class="literal">Button</code> objects, each
one an instance of the same class. Furthermore, two <code class="literal">Button</code> instances might contain different data,
perhaps giving each a different appearance and performing a different
action. In this sense, a class can be considered a mold for making the
object it represents, something like a cookie cutter stamping out
working instances of itself in the memory of the computer. As you’ll see
later, there’s a bit more to it than that—a class can in fact share
information among its instances—but this explanation suffices for now.
<a class="xref" href="ch05.html" title="Chapter 5. Objects in Java">Chapter 5</a> has the whole story on classes and
objects.</p><p>The term <span class="emphasis"><em>object</em></span> is very general and in some
other contexts is used almost interchangeably with
<span class="emphasis"><em>class</em></span>. Objects are the abstract entities that all
object-oriented languages refer to in one form or another. We will use
<span class="emphasis"><em>object</em></span> as a generic term for an instance of a
class. We might, therefore, refer to an instance of the <code class="literal">Button</code> class as a button, a <code class="literal">Button</code> object, or, indiscriminately, as an
object.</p><p>The <code class="literal">main()</code> method in the
previous example creates a single instance of the <code class="literal">JLabel</code> class and shows it in an instance of
the <code class="literal">JFrame</code> class. You could modify
<code class="literal">main()</code> to create many instances of
<code class="literal">JLabel</code>, perhaps each in a separate
window.</p></div><div class="sect2" title="Variables and Class Types"><div class="titlepage"><div><div><h2 class="title"><a id="learnjava3-CHP-2-SECT-2.4"/>Variables and Class Types</h2></div></div></div><p><a id="idx10051" class="indexterm"/> <a id="idx10065" class="indexterm"/> <a id="idx10088" class="indexterm"/> <a id="idx10111" class="indexterm"/>In Java, every class defines a new <a id="I_indexterm2_id637328" class="indexterm"/><span class="emphasis"><em>type</em></span> (data type). A variable can be
declared to be of this type and then hold instances of that class. A
variable could, for example, be of type <code class="literal">Button</code> and hold an instance of the <code class="literal">Button</code> class, or of type <code class="literal">SpreadSheetCell</code> and hold a <code class="literal">SpreadSheetCell</code> object, just as it could be
any of the simpler types, such as <a id="I_indexterm2_id637361" class="indexterm"/><code class="literal">int</code> or <a id="I_indexterm2_id637371" class="indexterm"/><code class="literal">float</code>, that represent
numbers. The fact that variables have types and cannot simply hold any
kind of object is another important feature of the language that ensures
the safety and correctness of code.</p><p>Ignoring the variables used inside the <code class="literal">main()</code> method for the moment, only one other
variable is declared in our simple <code class="literal">HelloJava</code> example. It’s found in the
declaration of the <code class="literal">main()</code> method
itself:</p><a id="I_2_tt24"/><pre class="programlisting"> <code class="kd">public</code> <code class="kd">static</code> <code class="kt">void</code> <code class="nf">main</code><code class="o">(</code> <code class="n">String</code> <code class="o">[]</code> <code class="n">args</code> <code class="o">)</code> <code class="o">{</code></pre><p>Just like functions in other languages, a method in Java declares
a list of variables that it accepts as <a id="I_indexterm2_id637416" class="indexterm"/><span class="emphasis"><em>arguments</em></span> or <a id="I_indexterm2_id637425" class="indexterm"/><span class="emphasis"><em>parameters</em></span>, and it specifies the
types of those variables. In this case, the main <code class="literal">method</code> is requiring that when it is invoked,
it be passed a list of <code class="literal">String</code> objects
in the variable named <code class="literal">args</code>. The
<code class="literal">String</code> is the fundamental object
representing text in Java. As we hinted earlier, Java uses the
<a id="I_indexterm2_id637456" class="indexterm"/><code class="literal">args</code> parameter to pass
any command-line arguments supplied to the Java virtual machine (VM)
into your application. (We don’t use them here.)</p><p>Up to this point, we have loosely referred to variables as holding
objects. In reality, variables that have class types don’t so much
contain objects as point to them. Class-type variables are references to
objects. A <a id="I_indexterm2_id637475" class="indexterm"/><span class="emphasis"><em>reference</em></span> is a pointer to or a handle
for an object. If you declare a class-type variable without assigning it
an object, it doesn’t point to anything. It’s assigned the default value
of <a id="I_indexterm2_id637487" class="indexterm"/><code class="literal">null</code>, meaning “no
value.” If you try to use a variable with a null value as if it were
pointing to a real object, a runtime error, <a id="I_indexterm2_id637500" class="indexterm"/><code class="literal">NullPointerException</code>,
occurs.</p><p>Of course, object references have to come from somewhere. In our
example, we created two objects using the <code class="literal">new</code> operator. We’ll examine object creation in
more detail a little later in the chapter.<a id="I_indexterm2_id637521" class="indexterm"/><a id="I_indexterm2_id637528" class="indexterm"/><a id="I_indexterm2_id637535" class="indexterm"/><a id="I_indexterm2_id637542" class="indexterm"/></p></div><div class="sect2" title="HelloComponent"><div class="titlepage"><div><div><h2 class="title"><a id="learnjava3-CHP-2-SECT-2.5"/>HelloComponent</h2></div></div></div><p><a id="idx10063" class="indexterm"/> <a id="idx10074" class="indexterm"/>Thus far, our <code class="literal">HelloJava</code>
example has contained itself in a single class. In fact, because of its
simple nature, it has really just served as a single, large method.
Although we have used a couple of objects to display our GUI message,
our own code does not illustrate any object-oriented structure. Well,
we’re going to correct that right now by adding a second class. To give
us something to build on throughout this chapter, we’re going to take
over the job of the <code class="literal">JLabel</code> class (bye
bye, <code class="literal">JLabel</code>!) and replace it with our
own graphical class: <code class="literal">HelloComponent</code>.
Our <code class="literal">HelloComponent</code> class will start
simple, just displaying our “Hello, Java!” message at a fixed position.
We’ll add capabilities later.</p><p>The code for our new class is very simple; we added just a few
more lines:</p><a id="I_2_tt25"/><pre class="programlisting"> <code class="kn">import</code> <code class="nn">java.awt.*</code><code class="o">;</code>
<code class="kd">class</code> <code class="nc">HelloComponent</code> <code class="kd">extends</code> <code class="n">JComponent</code> <code class="o">{</code>
<code class="kd">public</code> <code class="kt">void</code> <code class="nf">paintComponent</code><code class="o">(</code> <code class="n">Graphics</code> <code class="n">g</code> <code class="o">)</code> <code class="o">{</code>
<code class="n">g</code><code class="o">.</code><code class="na">drawString</code><code class="o">(</code> <code class="s">"Hello, Java!"</code><code class="o">,</code> <code class="mi">125</code><code class="o">,</code> <code class="mi">95</code> <code class="o">);</code>
<code class="o">}</code>
<code class="o">}</code></pre><p>You can add this text to the <span class="emphasis"><em>HelloJava.java</em></span>
file, or you can place it in its own file called
<span class="emphasis"><em>HelloComponent.java</em></span>. If you put it in the same
file, you must move the new <code class="literal">import</code>
statement to the top of the file, along with the other one. To use our
new class in place of the <code class="literal">JLabel</code>,
simply replace the two lines referencing the label with:</p><a id="I_2_tt26"/><pre class="programlisting"> <code class="n">frame</code><code class="o">.</code><code class="na">add</code><code class="o">(</code> <code class="k">new</code> <code class="n">HelloComponent</code><code class="o">()</code> <code class="o">);</code></pre><p>This time when you compile <span class="emphasis"><em>HelloJava.java</em></span>,
you will see two binary class files:
<span class="emphasis"><em>HelloJava.class</em></span> and
<span class="emphasis"><em>HelloComponent.class</em></span> (regardless of how you
arranged the source). Running the code should look much like the
<code class="literal">JLabel</code> version, but if you resize the
window, you’ll notice that our class does not automatically adjust to
center the code.</p><p>So what have we done, and why have we gone to such lengths to
insult the perfectly good <code class="literal">JLabel</code>
component? We’ve created our new <code class="literal">HelloComponent</code> class, <a id="I_indexterm2_id637694" class="indexterm"/><span class="emphasis"><em>extending</em></span> a generic graphical class
called <a id="I_indexterm2_id637703" class="indexterm"/><code class="literal">JComponent</code>. To extend a
class simply means to add functionality to an existing class, creating a
new one. We’ll get into that in the next section. Here we have created a
new kind of <code class="literal">JComponent</code> that contains
a method called <a id="I_indexterm2_id637723" class="indexterm"/><code class="literal">paintComponent()</code>, which
is responsible for drawing our message. Our <code class="literal">paintComponent()</code> method takes one argument
named (somewhat tersely) <code class="literal">g</code>, which is
of type <a id="I_indexterm2_id637745" class="indexterm"/><code class="literal">Graphics</code>. When the
<code class="literal">paintComponent()</code> method is invoked, a
<code class="literal">Graphics</code> object is assigned to
<code class="literal">g</code>, which we use in the body of the
method. We’ll say more about <code class="literal">paintComponent()</code> and the <code class="literal">Graphics</code> class in a moment. As for why, you’ll
understand when we add all sorts of new features to our new component
later on.<a id="I_indexterm2_id637787" class="indexterm"/><a id="I_indexterm2_id637794" class="indexterm"/></p></div><div class="sect2" title="Inheritance"><div class="titlepage"><div><div><h2 class="title"><a id="learnjava3-CHP-2-SECT-2.6"/>Inheritance</h2></div></div></div><p><a id="idx10075" class="indexterm"/> <a id="idx10090" class="indexterm"/>Java classes are arranged in a parent-child hierarchy in
which the parent and child are known as the <a id="I_indexterm2_id637837" class="indexterm"/><span class="emphasis"><em>superclass</em></span> and
<span class="emphasis"><em>subclass</em></span>, respectively. We’ll explore these
concepts fully in <a class="xref" href="ch06.html" title="Chapter 6. Relationships Among Classes">Chapter 6</a>. In Java, every
class has exactly one superclass (a single parent), but possibly many
subclasses. The only exception to this rule is the <a id="I_indexterm2_id637855" class="indexterm"/><code class="literal">Object</code> class, which
sits atop the entire class hierarchy; it has no superclass.</p><p>The declaration of our class in the previous example uses the
keyword <a id="I_indexterm2_id637869" class="indexterm"/><code class="literal">extends</code> to specify that
<code class="literal">HelloComponent</code> is a subclass of the
<code class="literal">JComponent</code> class:</p><a id="I_2_tt27"/><pre class="programlisting"> <code class="kd">public</code> <code class="kd">class</code> <code class="nc">HelloComponent</code> <code class="kd">extends</code> <code class="n">JComponent</code> <code class="o">{</code> <code class="o">...</code> <code class="o">}</code></pre><p>A subclass may inherit some or all the variables and methods of
its superclass. Through inheritance, the subclass can use those
variables and methods as if it has declared them itself. A subclass can
add variables and methods of its own, and it can also <a id="I_indexterm2_id637904" class="indexterm"/><span class="emphasis"><em>override</em></span> or change the meaning of
inherited methods. When we use a subclass, overridden methods are hidden
(replaced) by the subclass’s own versions of them. In this way,
inheritance provides a powerful mechanism whereby a subclass can refine
or extend the functionality of its superclass.</p><p>For example, the hypothetical spreadsheet class might be
subclassed to produce a new scientific spreadsheet class with extra
mathematical functions and special built-in constants. In this case, the
source code for the scientific spreadsheet might declare methods for the
added mathematical functions and variables for the special constants,
but the new class automatically has all the variables and methods that
constitute the normal functionality of a spreadsheet; they are inherited
from the parent spreadsheet class. This also means that the scientific
spreadsheet maintains its identity as a spreadsheet, and we can use the
extended version anywhere the simpler spreadsheet could be used. That
last sentence has profound implications, which we’ll explore throughout
the book. It means that specialized objects can be used in place of more
generic objects, customizing their behavior without changing the
underlying application. This is called <a id="I_indexterm2_id637941" class="indexterm"/><span class="emphasis"><em>polymorphism</em></span> and is one of the
foundations of object-oriented programming.</p><p>Our <code class="literal">HelloComponent</code> class is a
subclass of the <code class="literal">JComponent</code> class and
inherits many variables and methods not explicitly declared in our
source code. This is what allows our tiny class to serve as a component
in a <code class="literal">JFrame</code>, with just a few
customizations.<a id="I_indexterm2_id637971" class="indexterm"/><a id="I_indexterm2_id637978" class="indexterm"/></p></div><div class="sect2" title="The JComponent Class"><div class="titlepage"><div><div><h2 class="title"><a id="learnjava3-CHP-2-SECT-2.7"/>The JComponent Class</h2></div></div></div><p><a id="idx10052" class="indexterm"/> <a id="idx10066" class="indexterm"/> The <code class="literal">JComponent</code> class
provides the framework for building all kinds of user interface
components. Particular components—such as buttons, labels, and list
boxes—are implemented as subclasses of <code class="literal">JComponent</code>.</p><p>We override methods in such a subclass to implement the behavior
of our particular component. This may sound restrictive, as if we are
limited to some predefined set of routines, but that is not the case at
all. Keep in mind that the methods we are talking about are ways to
interact with the windowing system. We don’t have to squeeze our whole
application in there. A realistic application might involve hundreds or
thousands of classes, with legions of methods and variables and many
threads of execution. The vast majority of these are related to the
particulars of our job (these are called <a id="I_indexterm2_id638051" class="indexterm"/><span class="emphasis"><em>domain</em></span> objects). The <code class="literal">JComponent</code> class and other predefined classes
serve only as a framework on which to base code that handles certain
types of user interface events and displays information to the
user.</p><p>The <a id="I_indexterm2_id638068" class="indexterm"/><code class="literal">paintComponent()</code> method
is an important method of the <code class="literal">JComponent</code> class; we override it to implement
the way our particular component displays itself on the screen. The
default behavior of <code class="literal">paintComponent()</code>
doesn’t do any drawing at all. If we hadn’t overridden it in our
subclass, our component would simply have been invisible. Here, we’re
overriding <code class="literal">paintComponent()</code> to do
something only slightly more interesting. We don’t override any of the
other inherited members of <code class="literal">JComponent</code>
because they provide basic functionality and reasonable defaults for
this (trivial) example. As <code class="literal">HelloJava</code>
grows, we’ll delve deeper into the inherited members and use additional
methods. We will also add some application-specific methods and
variables specifically for the needs of <code class="literal">HelloComponent</code>.</p><p><code class="literal">JComponent</code> is really the tip of
another iceberg called Swing. Swing is Java’s user interface toolkit,
represented in our example by the <code class="literal">import</code> statement at the top; we’ll discuss it
in some detail in Chapters <a class="xref" href="ch16.html" title="Chapter 16. Swing">16</a> through <a class="xref" href="ch18.html" title="Chapter 18. More Swing Components">18</a>.<a id="I_indexterm2_id638151" class="indexterm"/><a id="I_indexterm2_id638158" class="indexterm"/></p></div><div class="sect2" title="Relationships and Finger Pointing"><div class="titlepage"><div><div><h2 class="title"><a id="learnjava3-CHP-2-SECT-2.8"/>Relationships and Finger Pointing</h2></div></div></div><p><a id="idx10085" class="indexterm"/>We can correctly refer to <code class="literal">HelloComponent</code> as a <code class="literal">JComponent</code> because subclassing can be thought
of as creating an “is a” relationship, in which the subclass “is a” kind
of its superclass. <code class="literal">HelloComponent</code> is
therefore a kind of <code class="literal">JComponent</code>. When
we refer to a kind of object, we mean any instance of that object’s
class or any of its subclasses. Later, we will look more closely at the
Java class hierarchy and see that <code class="literal">JComponent</code> is itself a subclass of the
<a id="I_indexterm2_id638218" class="indexterm"/><code class="literal">Container</code> class, which
is further derived from a class called <a id="I_indexterm2_id638230" class="indexterm"/><code class="literal">Component</code>, and so on,
as shown in <a class="xref" href="ch02s03.html#learnjava3-CHP-2-FIG-2" title="Figure 2-6. Part of the Java class hierarchy">Figure 2-6</a>.</p><p>In this sense, a <code class="literal">HelloComponent</code>
object is a kind of <code class="literal">JComponent</code>, which
is a kind of <code class="literal">Container</code>, and each of
these can ultimately be considered to be a kind of <code class="literal">Component</code>. It’s from these classes that
<code class="literal">HelloComponent</code> inherits its basic GUI
functionality and (as we’ll discuss later) the ability to have other
graphical components embedded within it as well.</p><div class="figure"><a id="learnjava3-CHP-2-FIG-2"/><div class="figure-contents"><div class="mediaobject"><a id="I_2_tt28"/><img src="httpatomoreillycomsourceoreillyimages1707604.png" alt="Part of the Java class hierarchy"/></div></div><p class="title">Figure 2-6. Part of the Java class hierarchy</p></div><p><code class="literal">Component</code> is a subclass of the
top-level <a id="I_indexterm2_id638304" class="indexterm"/><code class="literal">Object</code> class, so all
these classes are types of <code class="literal">Object</code>.
Every other class in the Java API inherits behavior from <code class="literal">Object</code>, which defines a few basic methods, as
you’ll see in <a class="xref" href="ch07.html" title="Chapter 7. Working with Objects and Classes">Chapter 7</a>. We’ll continue to use
the word <span class="emphasis"><em>object</em></span> (lowercase <span class="emphasis"><em>o</em></span>)
in a generic way to refer to an instance of any class; we’ll use
<code class="literal">Object</code> to refer specifically to the
type of that class.<a id="I_indexterm2_id638346" class="indexterm"/></p></div><div class="sect2" title="Package and Imports"><div class="titlepage"><div><div><h2 class="title"><a id="learnjava3-CHP-2-SECT-2.9"/>Package and Imports</h2></div></div></div><p><a id="idx10084" class="indexterm"/> <a id="idx10089" class="indexterm"/> <a id="idx10104" class="indexterm"/>We mentioned earlier that the first line of our example
tells Java where to find some of the classes that we’ve been
using:</p><a id="I_2_tt29"/><pre class="programlisting"> <code class="kn">import</code> <code class="nn">javax.swing.*</code><code class="o">;</code></pre><p>Specifically, it tells the compiler that we are going to be using
classes from the Swing GUI toolkit (in this case, <code class="literal">JFrame</code>, <code class="literal">JLabel</code>, and <code class="literal">JComponent</code>). These classes are organized into
a Java <span class="emphasis"><em>package</em></span> called <a id="I_indexterm2_id638437" class="indexterm"/><code class="literal">javax.swing</code>. A Java
package is a group of classes that are related by purpose or by
application. Classes in the same package have special access privileges
with respect to one another and may be designed to work together
closely.</p><p><a id="I_indexterm2_id638451" class="indexterm"/> <a id="I_indexterm2_id638457" class="indexterm"/>Packages are named in a hierarchical fashion with
dot-separated components, such as <code class="literal">java.util</code> and <code class="literal">java.util.zip</code>. Classes in a package must
follow conventions about where they are located in the classpath. They
also take on the name of the package as part of their “full name” or, to
use the proper terminology, their <span class="emphasis"><em>fully qualified
name</em></span>. For example, the fully qualified name of the <code class="literal">JComponent</code> class is <code class="literal">javax.swing.JComponent</code>. We could have referred
to it by that name directly, in lieu of using the <code class="literal">import</code> statement:</p><a id="I_2_tt30"/><pre class="programlisting"> <code class="kd">public</code> <code class="kd">class</code> <code class="nc">HelloComponent</code> <code class="kd">extends</code> <code class="n">javax</code><code class="o">.</code><code class="na">swing</code><code class="o">.</code><code class="na">JComponent</code> <code class="o">{...}</code></pre><p>The statement <code class="literal">import
javax.swing.*</code> enables us to refer to all the classes in the
<code class="literal">javax.swing</code> package by their simple
names. So we don’t have to use fully qualified names to refer to the
<code class="literal">JComponent</code>, <code class="literal">JLabel</code>, and <code class="literal">JFrame</code> classes.</p><p>As we saw when we added our second example class, there may be one
or more <code class="literal">import</code> statements in a given
Java source file. The <code class="literal">import</code>s
effectively create a “search path” that tells Java where to look for
classes that we refer to by their simple, unqualified names. (It’s not
really a path, but it avoids ambiguous names that can create errors.)
The <code class="literal">import</code>s we’ve seen use the dot
star (<code class="literal">.*</code>) notation to indicate that
the entire package should be imported. But you can also specify just a
single class. For example, our current example uses only the <code class="literal">Graphics</code> class from the <a id="I_indexterm2_id638578" class="indexterm"/><code class="literal">java.awt</code> package. So we
could have used <code class="literal">import
java.awt.Graphics</code> instead of using the wildcard <a id="I_indexterm2_id638595" class="indexterm"/><a id="I_indexterm2_id638603" class="indexterm"/><code class="literal">*</code> to import all the
<a id="I_indexterm2_id638618" class="indexterm"/><a id="I_indexterm2_id638623" class="indexterm"/>Abstract Window Toolkit (AWT) package’s classes. However,
we are anticipating using several more classes from this package
later.</p><p>The <code class="literal">java.</code> and <code class="literal">javax.</code> package hierarchies are special. Any
package that begins with <code class="literal">java.</code> is
part of the core Java API and is available on any platform that supports
Java. The <a id="I_indexterm2_id638652" class="indexterm"/><code class="literal">javax.</code> package normally
denotes a standard extension to the core platform, which may or may not
be installed. However, in recent years, many standard extensions have
been added to the core Java API without renaming them. The <code class="literal">javax.swing</code> package is an example; it is part
of the core API in spite of its name. <a class="xref" href="ch02s03.html#learnjava3-CHP-2-FIG-3" title="Figure 2-7. Some core Java packages">Figure 2-7</a> illustrates some of the core Java
packages, showing a representative class or two from each.</p><div class="figure"><a id="learnjava3-CHP-2-FIG-3"/><div class="figure-contents"><div class="mediaobject"><a id="I_2_tt31"/><img src="httpatomoreillycomsourceoreillyimages1707605.png" alt="Some core Java packages"/></div></div><p class="title">Figure 2-7. Some core Java packages</p></div><p><code class="literal">java.lang</code> contains fundamental
classes needed by the Java language itself; this package is imported
automatically and that is why we didn’t need an <code class="literal">import</code> statement to use class names such as
<code class="literal">String</code> or <code class="literal">System</code> in our examples. The <code class="literal">java.awt</code> package contains classes of the
older, graphical Abstract Window Toolkit; <code class="literal">java.net</code> contains the networking classes; and
so on.</p><p>As you gain more experience with Java, you will come to realize
that having a command of the packages available to you, what they do,
when to use them, and how to use them is a critical part of becoming a
successful Java developer.<a id="I_indexterm2_id638736" class="indexterm"/><a id="I_indexterm2_id638743" class="indexterm"/><a id="I_indexterm2_id638750" class="indexterm"/></p></div><div class="sect2" title="The paintComponent() Method"><div class="titlepage"><div><div><h2 class="title"><a id="learnjava3-CHP-2-SECT-2.10"/>The paintComponent() Method</h2></div></div></div><p><a id="idx10082" class="indexterm"/> <a id="idx10101" class="indexterm"/> <a id="idx10105" class="indexterm"/>The source for our <code class="literal">HelloComponent</code> class defines a method,
<code class="literal">paintComponent()</code>, that overrides the
<code class="literal">paintComponent()</code> method of the
<code class="literal">JComponent</code> class:</p><a id="I_2_tt32"/><pre class="programlisting"> <code class="kd">public</code> <code class="kt">void</code> <code class="nf">paintComponent</code><code class="o">(</code> <code class="n">Graphics</code> <code class="n">g</code> <code class="o">)</code> <code class="o">{</code>
<code class="n">g</code><code class="o">.</code><code class="na">drawString</code><code class="o">(</code> <code class="s">"Hello, Java!"</code><code class="o">,</code> <code class="mi">125</code><code class="o">,</code> <code class="mi">95</code> <code class="o">);</code>
<code class="o">}</code></pre><p>The <code class="literal">paintComponent()</code> method is
called when it’s time for our example to draw itself on the screen. It
takes a single argument, a <code class="literal">Graphics</code>
object, and doesn’t return any type of value (<code class="literal">void</code>) to its caller.</p><p><a id="I_indexterm2_id638862" class="indexterm"/> <span class="emphasis"><em>Modifiers</em></span> are keywords placed before
classes, variables, and methods to alter their accessibility, behavior,
or semantics. <code class="literal">paintComponent()</code> is
declared as <a id="I_indexterm2_id638878" class="indexterm"/><code class="literal">public</code>, which means it
can be invoked (called) by methods in classes other than <code class="literal">HelloComponent</code>. In this case, it’s the Java