Sie sind auf Seite 1von 161

Java Programming 1: Introduction to Java and the Eclipse Development

Environment
Lesso n 1: Int ro duct io n t o J ava
Windo ws Settings
An Applet
Using Eclipse
Our Seco nd Applet
Java is an Object-Oriented Language
Structured Pro gramming
Lesso n 2: Obje ct -Orie nt e d Pro gram m ing
Intro ductio n
What is Object-Oriented Pro gramming?
Demystifying the Pro gram
Reading Co de
What Abo ut the Other One?
Hierarchy Structure in Eclipse
Lesso n 3: Apple t s
Applets
What Can Applets Do ?
Getting Images
Applet Uses Other Classes
Lesso n 4: An Apple t 's Lif e Cycle
Applets Co ntinued
Applet Life Cycle
Adding Metho ds
Co ntro l
Watching a Life
Lesso n 5: De cisio ns, De cisio ns, De cisio ns
Pro gram Co ntro l Using If Statements
If Statements
Placement o f Blo ck Braces
Co mpariso n Operato rs and Lo gic
Co mpariso n Operato rs
Lesso n 6 : Obje ct s and Classe s
Objects
What is an Object?
Classes
Java Data Types
Lesso n 7: Classe s and Inst ance s
Object Design
Who gets what?

Initializatio n and Co nstructo rs


Making an Applet fo r Dukes
Ano ther Applet fo r Dukes
Lesso n 8 : Using t he API: Int ro duct o ry Graphics
Using Java Pro vided Classes
java.awt.Graphics Class
Using the API
Metho ds, Parameters (o r Arguments), and the Do t Operato r
Sequencing
The java.awt.Co lo r Class
Lesso n 9 : Drawing wit h Graphics
Making Pictures
Back to Graphics
Lesso n 10 : Me t ho ds and Me t ho d Invo cat io n
Metho ds
Creating and Using Metho ds
Tracing metho d calls
Lesso n 11: Writ ing Classe s - Building Wit h Me t ho ds
Mo re o n Metho ds
Lo cal Variables
Results and Return
Building o n metho ds
Overlo ading
Ho w Do es Java Find the Right Metho d?
Summary
Metho d Declaratio ns
main: an impo rtant metho d
Lesso n 12: Adding Int e ract io n using Co m po ne nt s and List e ne rs
Revisiting the Dukes Class and Applet
A User Mo dificatio n Example
Intro ductio n to Interfaces
An Analo gy: Antenna as an Interface
The Listener Interfaces
Lesso n 13: Mo dularit y: Mo dif ie rs, Pe rm issio ns, and Sco pe
Class Specificatio ns
Mo dularity
Mo difiers
Access Mo difiers--Permissio ns
What Permissio ns Allo w
Lesso n 14: Class Me m be rs, Co nst ant s and m ain
Static Members
Static: Making Yo ur Own

static and main


Co nstructo rs
Instantiatio n
Co nstants use the final mo difier
Template and Summary
Lesso n 15: All T o ge t he r No w
Interactio n and Playing Aro und
Putting It All To gether
Using Inheritance o n o ur Own

Copyright 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Introduction to Java
Welco me to the O'Reilly Scho o l o f Techno lo gy's Java Pro gramming 1 co urse, Intro ductio n to Java and the Eclipse Integrated
Develo pment Enviro nment (IDE).

Course Objectives
When yo u co mplete this co urse, yo u will be able to :
build Java applicatio ns and applets in the Eclipse IDE.
create co ntro l structures, classes, o bjects, and metho ds.
add interactio n to pro grams using co mpo nents and listeners.
apply the Java API to draw graphics.
demo nstrate understanding o f mo dularity, mo difiers, permissio ns, sco pe, and inheritance.
When yo u co mplete this lesso n, yo u will be able to :

Lesson Objectives
access vario us O'Reilly Scho o l o f Techno lo gy to o ls.
define and create an applet.
In this co urse, yo u'll learn the fundamental co ncepts and syntax o f the Java pro gramming language. Thro ugho ut this co urse,
yo u will build examples using the Eclipse Java IDE, which is supplied as a Learning Sandbo x. Co mpletio n o f this co urse will
give yo u a basic understanding o f Object-Oriented techniques in Java, as well as using the Eclipse IDE.
Fro m beginning to end, yo u'll learn by do ing yo ur o wn Java pro jects, within the Eclipse Learning Sandbo x we affectio nately call
"Ellipse." These pro jects will add to yo ur po rtfo lio and pro vide needed experience. All yo u need is a bro wser and internet
co nnectio n we pro vide all the so ftware yo u need o nline.

Learning with O'Reilly School of T echnology Courses


As with every O'Reilly Scho o l o f Techno lo gy co urse, we'll take a user-active appro ach to learning. This means that yo u
(the user) will be active! Yo u'll learn by do ing, building live pro grams, testing them and experimenting with them
hands-o n!
To learn a new skill o r techno lo gy, yo u have to experiment. The mo re yo u experiment, the mo re yo u learn. Our system
is designed to maximize experimentatio n and help yo u learn to learn a new skill.
We'll pro gram as much as po ssible to be sure that the principles sink in and stay with yo u.
Each time we discuss a new co ncept, yo u'll put it into co de and see what YOU can do with it. On o ccasio n we'll even
give yo u co de that do esn't wo rk, so yo u can see co mmo n mistakes and ho w to reco ver fro m them. Making mistakes
is actually ano ther go o d way to learn.
Abo ve all, we want to help yo u to learn to learn. We give yo u the to o ls to take co ntro l o f yo ur o wn learning experience.
When yo u co mplete an OST co urse, yo u kno w the subject matter, and yo u kno w ho w to expand yo ur kno wledge, so
yo u can handle changes like so ftware and o perating system updates.
Here are so me tips fo r using O'Reilly Scho o l o f Techno lo gy co urses effectively:
T ype t he co de . Resist the temptatio n to cut and paste the example co de we give yo u. Typing the co de
actually gives yo u a feel fo r the pro gramming task. Then play aro und with the examples to find o ut what else
yo u can make them do , and to check yo ur understanding. It's highly unlikely yo u'll break anything by
experimentatio n. If yo u do break so mething, that's an indicatio n to us that we need to impro ve o ur system!
T ake yo ur t im e . Learning takes time. Rushing can have negative effects o n yo ur pro gress. Slo w do wn and
let yo ur brain abso rb the new info rmatio n tho ro ughly. Taking yo ur time helps to maintain a relaxed, po sitive
appro ach. It also gives yo u the chance to try new things and learn mo re than yo u o therwise wo uld if yo u
blew thro ugh all o f the co ursewo rk to o quickly.
Expe rim e nt . Wander fro m the path o ften and explo re the po ssibilities. We can't anticipate all o f yo ur
questio ns and ideas, so it's up to yo u to experiment and create o n yo ur o wn. Yo ur instructo r will help if yo u
go co mpletely o ff the rails.

go co mpletely o ff the rails.


Acce pt guidance , but do n't de pe nd o n it . Try to so lve pro blems o n yo ur o wn. Go ing fro m
misunderstanding to understanding is the best way to acquire a new skill. Part o f what yo u're learning is
pro blem so lving. Of co urse, yo u can always co ntact yo ur instructo r fo r hints when yo u need them.
Use all available re so urce s! In real-life pro blem-so lving, yo u aren't bo und by false limitatio ns; in OST
co urses, yo u are free to use any reso urces at yo ur dispo sal to so lve pro blems yo u enco unter: the Internet,
reference bo o ks, and o nline help are all fair game.
Have f un! Relax, keep practicing, and do n't be afraid to make mistakes! Yo ur instructo r will keep yo u at it
until yo u've mastered the skill. We want yo u to get that satisfied, "I'm so co o l! I did it!" feeling. And yo u'll have
so me pro jects to sho w o ff when yo u're do ne.

Windows Settings
If yo u like, yo u can set yo ur o wn Windo ws mo use, keybo ard, and regio n; fo r example, if yo u are left-handed, yo u can
switch the left and right butto n functio nality o n the mo use, o r yo u can change date fields to use date fo rmats fo r yo ur
lo cal regio n. Click the do wn arro w o n the Windo ws Settings butto n at the to p right o f the screen:

We wo n't discuss the details o f these dialo g bo xes, but feel free to ask yo ur instructo r if yo u have questio ns.

No w, befo re we get started pro gramming in Java, let me sho w yo u ho w the material will be presented.

Lesson Format

We'll try o ut lo ts o f examples in each lesso n. We'll have yo u write co de, lo o k at co de, and edit existing co de. The co de
will be presented in bo xes that will indicate what needs to be do ne to the co de inside.
Whenever yo u see white bo xes like the o ne belo w, yo u'll type the co ntents into the edito r windo w to try the example
yo urself. The CODE TO TYPE bar o n to p o f the white bo x co ntains directio ns fo r yo u to fo llo w:
CODE TO TYPE:
White boxes like this contain code for you to try out (type into a file to run).
If you have already written some of the code, new code for you to add looks like this.
If we want you to remove existing code, the code to remove will look like this.
We may also include instructive comments that you don't need to type.
We may run pro grams and do so me o ther activities in a terminal sessio n in the o perating system o r o ther co mmandline enviro nment. These will be sho wn like this:
INTERACTIVE SESSION:
The plain black text that we present in these INTERACTIVE boxes is
provided by the system (not for you to type). The commands we want you to type look lik
e this.

Co de and info rmatio n presented in a gray OBSERVE bo x is fo r yo u to inspect and absorb. This info rmatio n is o ften
co lo r-co ded, and fo llo wed by text explaining the co de in detail:
OBSERVE:
Gray "Observe" boxes like this contain information (usually code specifics) for you to
observe.
The paragraph(s) that fo llo w may pro vide additio n details o n inf o rm at io n that was highlighted in the Observe bo x.
We'll also set especially pertinent info rmatio n apart in "No te" bo xes:

Note
T ip

No tes pro vide info rmatio n that is useful, but no t abso lutely necessary fo r perfo rming the tasks at hand.

Tips pro vide info rmatio n that might help make the to o ls easier fo r yo u to use, such as sho rtcut keys.

WARNING

Warnings pro vide info rmatio n that can help prevent pro gram crashes and data lo ss.

An Applet
If yo u're new to pro gramming, allo w me to intro duce yo u to the "Hello Wo rld" example. Traditio nally it's the first
pro gram yo u write in any language. I wo uld bet that a "Hello Wo rld" pro gram has been written in every co mputer
language.

Using Eclipse
The pro gram filling up yo ur screen right no w is an Integrated Develo pment Enviro nment (IDE) called Eclipse.
An IDE is essentially an edito r that is custo mized to help yo u to pro gram. Our IDE, Eclipse, is custo mized to
help yo u with Java.
We're inching ever clo ser to making so mething, but first we need to set up the enviro nment fo r o ur first file. In
Eclipse, all files must be within projects. In this co urse, a project is the same thing as a folder.

To start o ur first pro ject, select File | Ne w | J ava Pro je ct :

Name yo ur pro ject. (We'll be making a who le lo t o f pro jects, so we'll cho o se names that will help us keep
them o rganized.) Call this o ne java1_Le sso n0 1, cho o se to Use de f ault jre (Java Runtime Enviro nment),
and be sure and put it in the J ava1_Le sso ns Working Set.

If yo u see the dialo g belo w, go ahead and check the Re m e m be r m y de cisio n bo x and then click No .

If yo u clicked Ye s o n the abo ve dialo g by mistake, select the Windo ws menu and click Pre f e re nce s. When
the dialo g appears, click J ava o n the left, adn then click Cle ar as sho wn:

No w yo u can see the java1_Le sso n0 1 pro ject listed in the Package Explo re r panel o n the lo wer-left co rner
o f yo ur screen:

This hierarchical view o f the reso urces (directo ries and files) in Eclipse is co mmo nly called the workspace.
Yo u no w have a pro ject named java1_Le sso n0 1 in yo ur wo rkspace.
Yo u pro bably no ticed items in the wo rkspace like J ava1_Le sso ns, J ava1_Ho m e wo rk, and so o n. We put
them there to help yo u stay o rganized. These are called working sets. A wo rking set is like a fo lder, but is
actually just an asso ciatio n o f files. The difference between a wo rking set and a fo lder is that a wo rking set
do esn't have any depth in the file system, so file and fo lder references do n't even see them. Yo u can turn
wo rking sets o n and o ff in Eclipse. Yo u can either turn all wo rking sets o ff o r turn o nly so me o f them o ff if

things get to o cluttered. Try it! Click the white do wn arro w o n the Package Explo rer tab:

No w that yo u've played aro und with wo rking sets, make sure they're all back in place. To easily sho w just the
wo rking sets fo r this co urse, click the small black do wn arro w o n the Sho w Wo rking Se t s butto n in the
Package Explo rer, then select J ava, and then J ava1:

We're abo ut to create a new class file to put into o ur pro ject. We'll talk abo ut classes in detail later, but right
no w, let's get go ing and make o ne!
Select java1_Le sso n0 1 in the Package Explo rer so it's highlighted. In the to p OST J ava - Eclipse SDK
menu bar, cho o se File | Ne w | Class as sho wn (if the Ne w submenu do esn't include Class, cho o se
Ot he r..., then do uble-click o n Class):

In yo ur New Java Class windo w, if So urce fo lder: do es no t already co ntain java1_Le sso n0 1/src, click
Bro wse ... to lo o k fo r and select the java1_Le sso n0 1/src fo lder (o r type java1_Le sso n0 1/src). Give yo ur
class the name He llo Wo rld as sho wn:

Click Finish. Yo u see this co ntent in the lo wer-right Editor Window:

This Edito r Windo w allo ws yo u to create, write, and o f co urse, edit co de.
No tice that the name o f the file fo r the co de is Hello Wo rld.java. Java source code always has the same name
as the class, fo llo wed by the .java extensio n.
Okay, no w let's add the co de fo r o ur first Applet! Type the co de in the edito r belo w as sho wn:

CODE TO TYPE:
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawRect(0, 0, 100, 100);
g.drawString("Hello World!", 5, 15);
}
}

If yo u see o ne o f these
beside the public class He llo Wo rld e xt e nds Apple t { line, just igno re it. This
symbo l is a warning that can be igno red fo r no w; it wo n't affect the running o f yo ur co de.
Eclipse has a special way o f running Applets, but they usually need to be run o n a web page. No w that we've
go t that co de typed, let's save and run it! Click in the Edito r Windo w where yo ur co de is written (the
Hello Wo rld.java file). In the very to p Eclipse menu bar (no t the O'Reilly tab bar), select File | Save :

There are a few different ways to save a file. Yo u can select File | Save as abo ve, o r click the

Note

Save ico n
in the Eclipse to o lbar, o r yo u can press Ct rl+S. In the future, when we want yo u
to save a file, we'll sho w the Save ico n.

No w, fro m the to p menu bar, select Run | Run As | J ava Apple t . (If J ava Apple t isn't there, go back to the
Edito r Windo w and click in the Hello Wo rld.java edito r and try again.)

T ip

As with saving, there's mo re than o ne way to run yo ur Java co de; just use the o ne yo u like best.
When we want yo u to run a pro gram, we'll sho w the Run ico n (

).

No w yo u have a small bro wser running in the upper-left co rner o f yo ur co mputer screen. The bro wser is
labeled Appletviewer and displays the o utput o f yo ur Applet. It prints o ut He llo Wo rld! inside a bo x:

Sweet! Yo u've o fficially created and run yo ur first Java Applet! To clo se the Appletviewer, click the x in the
upper-right co rner.

Our Second Applet


The next Applet we'll create is similar to the first o ne, but it uses different co de. To begin, we'll create a new Class file in
java1_Lesso n0 1, and name it He llo Wo rld2.
Here's ano ther way to create a class. Right-click the java1_Le sso n0 1/src fo lder in the Package Explo rer, and select
Ne w | Class:

Name it He llo Wo rld2 in the dialo g bo x:

No w let's give He llo Wo rld2 so me co de.


Type the co de belo w (serio usly, type the co de, do n't just cut and paste!) into the He llo Wo rld2 file as sho wn:
CODE TO TYPE:
import java.awt.*;
import javax.swing.*;
public class HelloWorld2 extends JApplet {
public void init() {
Container contentPane = getContentPane();
JLabel label = new JLabel("Hello Again, World!", SwingConstants.CENTER);
contentPane.add(label);
}
}
No w save and run it, using the Eclipse File and Run menus like we did earlier (o r yo u can use the

sho rtcut).

Yes, yo u've do ne it again! This Applet lo o ks a little different fro m yo ur first o ne, but it do es ro ughly the same thing.
Go o d jo b! Again, click the upper-right x to clo se the Appletviewer.

Java is an Object-Oriented Language


Structured Programming
In o rder to appreciate o bject-o riented pro gramming, let's take a lo o k at its predecesso rs: procedural
languages, such as C and Fo rtran. They co nsist o f procedures o r routines which simply co ntain a series o f
co mputatio nal steps to be fo llo wed.
The very first construct o f co mputing is sequencing, which means the co de fo llo ws the lines in sequence, o ne
after the o ther. If a pro grammer makes mistakes and a language isn't meticulo usly written, the steps co uld be
hard to figure o ut. Here's an example o f such a pro gram in a pro cedural language:
OBSERVE:
10
20
30
40
50
60
70
80
90

i = 0
i = i + 1
if i <= 10 then goto 80
if i > 10 then goto 60
goto 20
print "Program Completed."
end
print i; " squared = "; i * i
goto 20

Let's trace (fo llo w the executio n o f) this pro gram. We'll go thro ugh each o f the steps and see what they do :

OBSERVE:
10: Set i to 0
20: Set i to i(0) + 1, or 1
30: Since i is now 1 and 1 is less than < 10, go to 80
80: Print the value of i (which here is 1), and the text " squared = ", and then
the product of i * i (here, it is 1)
90: Go to line 20
20: Set i to i(now 1) + 1, or 2
30: Since i is now 2 and 2 is still less than < 10, go to 80 again
80: Print the value of i (which here is 2), and the text " squared = ", and then
the product of i * i (now, it is 4)
90: Go to line 20
20: Set i to i(now 2) + 1, or 3
... It continues looping until i is 10 or more at line 30, at which point it pas
ses to...
40: Go to line 60
60: Print "Program Completed."
70: End the program
The same pro gram in a structured programming language wo uld lo o k so mething like this:
OBSERVE:
for i = 1 to 10
print i; " squared = "; i * i
next i
print "Program Completed."
No tice that yo u do n't need to include the line numbers in yo ur co de. The co de is structured in such a way that
it do esn't send yo u all o ver the place! Structured co de is preferred because:
it's easier to fo llo w.
it's easier to pro ve that it is co rrect.
it's easier to debug.
it's mo re co ncise.
Object-oriented programming was develo ped to avo id the co mmo n pitfalls o f procedural programming.
Let's create and run that pro gram in Java to see ho w well Duke handles it!
Create a new class in the J ava1_Le sso n0 1 pro ject named St ruct ure dDe m o .
Go ahead, we'll wait.
No w, type the co de into St ruct ure dDe m o as sho wn:
CODE TO TYPE:
import java.awt.*;
import java.applet.Applet;
public class StructuredDemo extends Applet {
public void paint(Graphics g){
for (int i=1; i <10; i++)
g.drawString(i + " squared = " + i*i, 10, 15*i);
g.drawString("Program Completed", 10, 180);
}
}
Run it. It wo rks great! When yo u finish, clo se the Appletviewer as befo re.
Nice! We have written no t one, no t two, but three Java Applets, and we've run them in the Eclipse IDE!

If yo u haven't clo sed them already, yo u can still see a tab fo r each pro gram at the bo tto m o f yo ur windo w. Click o n the
x in each o ne's tab to clo se them, o r Eclipse will clo se them fo r yo u when yo u Exit.
Go o d jo b so far, but we're just getting started!
No w, go back to the syllabus page by clicking the Back butto n and co mplete any Quizzes and Pro jects fo r this lesso n.
See yo u in the next lesso n!
Copyright 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Object-Oriented Programming
When yo u co mplete this lesso n, yo u will be able to :

Lesson Objectives
determine which o bjects we have at o ur dispo sal.
use o bjects to make mo re o bjects to perfo rm additio nal tasks.
access classes fro m the Java API.
use mo difiers o n Java classes.
use actio ns o r m e t ho ds with classes.
pass o bjects to metho ds.
view the Java hierarchy structure.

Introduction
What is Object-Oriented Programming?
Every piece o f co de that makes up an o bject-o riented pro gram is kno wn as an object. The co de
representatio n o f an o bject is a class, and classes pro duce objects. Think o f an o bject like a cake that yo u
bake. A cake can have all kinds o f pro perties: shape, flavo r, icing, and so o n. To co ntinue with this analo gy, a
class is like a particular cake mo ld. Each instance o f cake made using that mo ld may be slightly different
because it has different pro perties. Other peo ple can use yo ur mo ld to make cakes that acco mplish their o wn
tasks. Keep this cake metapho r in mind as we co ntinue to discuss classes, o bjects, instances, and
pro perties.

A class is like
a cake mo ld fo r
making cake
o bjects.

Creating a
cake object

A cake object
with pro perties
Pink Icing and
Strawberry o n To p.

In Java, every o bject has properties and methods. The pro perties determine an o bject's current state, while
metho ds are actio ns that can alter that state. Classes are no uns, and metho ds are verbs! Fo r instance, we
might EAT a cake. So EAT co uld be a cake's metho d in Java.
To write an o bject-o riented pro gram:
1. Determine which o bjects we already have at o ur dispo sal.
2. Use these o bjects to make mo re o bjects to perfo rm additio nal tasks.
When we pro gram in Java, we're telling o bjects what to do to each o ther. After a Java pro gram is written, o ther
pro grammers can create new classes aro und the o bjects in the pro gram, and then we can use tho se new
o bjects to o . Objects in Java allo w pro grammers to co o perate and share.
Alo ng with Java, there is a library o f o bjects fo r everyo ne to use as a base. Over time, the library has gro wn.
Each new versio n o f Java no t o nly fixes pro blems (bugs) fo und in previo us versio ns, but pro vides us with
even mo re o bjects (classes) to use. In o rder to do o bject-o riented pro gramming, yo u'll want to beco me
familiar with the library o f available classes. The library is pro vided o nline by Oracle, and is called the
Applicatio n Pro gramming Interface (API).
Whenever we're lo o king at a class in the API, we'll give yo u a heads-up with o ne o f these API ico ns:

, API, o r
To see the API page, click the link. Clo sing the windo w o r clicking o n the Le sso n Vie w tab will bring yo u back
here.
The API is also called the Class Library. No tice that the Oracle page has API do cuments fo r numero us
versio ns o f Java. Usually yo u'll want to run the newest versio n o f Java because the newer versio ns have
fixed mo re bugs and have made mo re classes available.
Lo o k o n yo ur menu fo r the
butto n in the ro w o f ico ns under the Eclipse menu bar. Click this to see the API
fo r the mo st current Java versio n. The mo re yo u pro gram with Java, the mo re yo u'll rely o n the API.
No w that we kno w so me OOP termino lo gy, let's lo o k at the o bjects in yo ur first pro gram.

Demystifying the Program


Reading Code
Once again, go to the Package Explo rer and o pen yo ur java1_Le sso n0 1 pro ject. In the src fo lder, find
He llo Wo rld.java and o pen it in the edito r.
Fo r no w, so we can wo rk thro ugh the co de, let's use line numbers next to the co de. To make line numbers
visible, right-click the vertical frame bar at the left o f the edito r windo w, and select Sho w Line Num be rs:

It's po ssible that yo u have "co llapsed" blo cks o f co de in yo ur pro gram. If yo u see a + sign next to the number
1 line o f yo ur co de, click o n it. If yo ur + sign is o n line 2, delete the empty line 1 by go ing to the beginning o f
line 2 in fro nt o f im po rt and pressing the Backspace key. No w yo ur line numbers sho uld match up.
Eclipse was simply "co llapsing" a blo ck o f co de lines to fo cus o n the o ther co de. The lines are all still there,
tho ugh. The plus sign (+) means "expand" (indicating co llapsed co de) and minus (-) means "co llapse"
(indicating there is a blo ck o f co de yo u can co llapse).

Okay, no w let's break the co de do wn o ne line at a time:


OBSERVE:
1. import java.applet.Applet;
This line tells Java that so mething in yo ur co de is go ing to use o ne o f tho se classes fro m the Java API; Java
will import all the stuff fo r yo u so that yo u can use it. Here the o bject type (class) we want to use is called
Apple t . Java can find this class in the package named java.apple t .
Packages are directo ries that ho ld a co llectio n o f related o bjects (classes). The java.apple t package
co ntains the Apple t class (a really useful class).
Go to the API page fo r the java.applet package. Click o n the link. Scro ll do wn to the Class Sum m ary and
click o n the Apple t class (we'll discuss the info rmatio n that the API gives us later).
Let's see what wo uld happen if we didn't impo rt the Applet package. Try remo ving the impo rt statement as
sho wn:
CODE TO TYPE:
1
2
3
4
5
6
7
8
9

import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawRect(0, 0, 100, 100);
g.drawString("Hello World!", 5, 15);
}
}

No w yo u'll see this:

See the light bulb and X in the red bo x o n the left panel? They're telling yo u that so mething's missing.
This means there's an erro r in o ur pro gram. Eclipse will no t run with erro rs, but fo rtunately, it suggests a
remedy. See ho w the wo rd Applet is underlined with a red zig-zag? Try mo ving yo ur mo use o ver it. It says
Apple t canno t be re so lve d t o a t ype .
That means that Eclipse can't identify Apple t because the package that co ntains the class Applet is no t
kno wn ("canno t be reso lved"), so the class info rmatio n is no t available.
If yo u click o n the light bulb, it will suggest ways to fix the pro blem. When yo u click o n o ne o f the suggested
remedies, Eclipse will implement it. Fo r instance, click o n the light bulb and then do uble-click o n the cho ice
im po rt 'Apple t ' (java.apple t ) to put it back in the co de.
If the impo rt statement fo r Applet is o n line 2, delete the empty line 1, so the numbers line up again.

The

ico n signifies erro rs. Yo u must fix these in o rder to run yo ur co de.

Note
The
ico n is o nly a warningJava is unco mfo rtable with so me part o f yo ur co de, but will
still run.
No w, back to o ur Hello Wo rld co de:
OBSERVE:
2 import java.awt.Graphics;
In line 2, we're impo rting ano ther class. Can yo u tell fro m the syntax o f the line which part is the package and
which part identifies the class? By co nventio n, package names begin with lo wer-case characters and classes
begin with upper-case letters. Our line o f co de ends with a ; (semico lo n). The semico lo n in Java syntax tells
the co mpiler that it has arrived at the end o f a line o f co de.
So in this case, java.awt is the package and Graphics is the class.
Yo u can learn mo re abo ut the Graphics class at:
1. API
2. java.awt
3. Graphics
We'll take a clo ser lo o k at the Graphics class in future lesso ns as well.
OBSERVE:
3
Line 3 is a blank line that helps make the co de easier to read. Here, it separates the blo ck o f impo rt
statements fro m the class definitio n.
OBSERVE:
4 public class HelloWorld extends Applet {
Line 4 signifies the beginning o f the definitio n o f o ur first class.
The first wo rd, public, is a modifier. The mo difier tells Java so mething abo ut accesswho can use the class
o r metho d o r variable. In this case, it's public. Fo r this particular co urse, all o f o ur classes will be public, but
many o f o ur metho ds and variables will be privat e o r pro t e ct e d. We'll explo re access mo re later, but if
yo u're curio us and want to kno w mo re right no w, go ahead and Go o gle "Java mo difiers."
The next keywo rd in o ur co de is class, which tells Java we're creating a class.
This particular class is called He llo Wo rld.
The keywo rd e xt e nds tells Java that we want Hello Wo rld to inherit all the Apple t co dewe are defining
Hello Wo rld to be an Applet. Ano ther o ptio n is im ple m e nt s, which we'll get into later to o .
At the beginning o f this lesso n, yo u ran an Applet. It o pened a windo w o n yo ur co mputer with a nice frame
aro und it and typed in wo rds fo r yo u. Yo u didn't have to type them in yo urself because Java already had a
class (Apple t ) written fo r yo u to implement. So , when yo u inherit a class that Java has already written (and
so is already present in the API), yo u get access to all o f its (the parent class's) pro perties.
The curly bracket, o r brace { at the end o f line 4 tells Java that instructio ns fo r the Hello Wo rld applet's task
begin there. We'll tell Java when o ur He llo Wo rld class definitio n is do ne by including a clo sing brace } o n
line 9 .
Yo u can see which pairs o f braces match up by clicking the mo use directly after an o pening o r clo sing brace
the matching brace will be highlighted o n the screen. In o ur example, if yo u try clicking right after the clo sing

curly bracket o n line 9 , the edito r makes a little bo x aro und the { o n line 4, so we kno w that tho se two brackets
match. This can be really handy in large pro grams!
Okay, so what's in the class? Take a lo o k:
OBSERVE:
5
6
7
8

public void paint(Graphics g) {


g.drawRect(0, 0, 100, 100);
g.drawString("Hello World!", 5, 15);
}

In lines 5-8 , we define a co mpo nent o f the He llo Wo rld class. We already kno w that classes may have
pro perties and actio ns. This particular class do esn't have pro perties yet, but it do es have an actio n available
(starting at line 5) called paint . In OOP, the actio ns that a class can take are called m e t ho ds. In this co de
yo u've defined the metho d paint (). Take ano ther lo o k at that blo ck o f co de:
OBSERVE:
public void paint(Graphics g) {
g.drawRect(0, 0, 100, 100);
g.drawString("Hello World!", 5, 15);
}
Similar to class definitio ns, all metho d definitio ns begin with a modifier. Here again we use the mo difier
public. The next keywo rd in the metho d definitio n (vo id) tells us the type o f o bject the metho d will re t urn.
This particular o bject do esn't return anything, so we use the keywo rd vo id. We use this keywo rd o n all
metho ds that do n't return o bjects. Do n't wo rry, we'll see so me metho ds that do return o bjects in o ur
upco ming lesso ns.
This metho d is passe d ano ther o bject called a Graphics area. The co de states that the Graphics area is
named g. We use metho ds fro m the Graphics o bject (co nveniently, so meo ne at Oracle has already created
that o bject). When we write so m e No un.so m e Ve rb(), we are telling Java to access the metho d called
so m e Ve rb() fro m the o bject so m e No un. In this case, we wro te g.drawRe ct (0 , 0 , 10 0 , 10 0 ); and
g.drawSt ring("Hello Wo rld!", 5, 15); because we knew the Graphics o bject has drawRe ct () and
drawSt ring() metho ds we can use. Ho w did we kno w all o f that? We lo o ked it up in the Java API!
This definitio n o f the paint () metho d creates a Graphics area fo r the Applet so yo u can "paint" o r "draw" o n it.
In this co de, yo u are drawing two things:
g.drawRe ct (0 , 0 , 10 0 , 10 0 ) tells the Applet to draw a rectangle o n the Graphics area g. The numbers in o ur
co de indicate the fo ur co rners o f o ur rectangle in pixels. I'll leave it to yo u to experiment to figure o ut which
number co rrespo nds to which co rner! Yo u can do that by changing the numbers and rerunning the Applet.
g.drawSt ring("Hello Wo rld!", 5, 15) is telling the Applet to draw the wo rds "Hello Wo rld" o n the Graphics
area g. The numbers indicate where yo u want to place the wo rds (string) o n the Graphics area. Again, I'll
leave it to yo u to experiment and play with the numbers.
Braces {} in Java are always matched with their nearest partner. The { at the end o f line 5 is clo sed with the }
at line 8 . Use the mo use click trick we learned earlier and see fo r yo urself. The { at the end o f line 4 is clo sed
with the } at line 9 .
No w let's change the size o f the rectangle and write so mething different o n the Applet.
If yo u do n't already have He llo Wo rld.java in the Edito r windo w, lo o k fo r a He llo Wo rld.java tab in the Edito r
windo w and click it. If there is no He llo Wo rld.java tab, o pen the java1_Le sso n0 1 fo lder and its default
package in the Package Explo rer area, then do uble-click the He llo Wo rld.java file. Edit the co de as sho wn
belo w:

CODE TO TYPE:
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
g.drawString("On to new things!", 5, 15);
}
}
Save and run it. Use the mo use to resize the Appletviewer windo w and no te ho w the bo x changes! Are
yo u impressed? (Remember to clo se the applet after running it.)
Let's change the line again to see what it do es:
CODE TO TYPE:
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawRect(0, 0, getSize().width - 50, getSize().height - 100);
g.drawString("I'm not really impressed yet", 5, 15);
}
}
Save and run it again.
Changing the two lines o f co de altered the size o f the surro unding rectangle and wro te different statements.
Clo se the Appletviewer, and try experimenting mo re with the rectangle size. Make sure to save and then run it.
Yo u can always refer to the o riginal co de abo ve, in case yo u really mess up!
No w let's go o ver class names. The class that we defined abo ve with the name He llo Wo rld must have the
file name He llo Wo rld.java.

WARNING

Java is case -se nsit ive and every character matters. The file must have the same name
as the class yo u define, plus the .java extensio n. So , if yo u change the class name, yo u
must change the file name as well.

In yo ur Hello Wo rld class, try to change yo ur name o f He llo Wo rld to He llo Wo rld6 . Yo u can view
suggestio ns by clicking o nce o n the light bulb warning. This trick is really handy fo r co rrecting erro rs.
In o ur example, yo u'll be instructed to rename the type (class) Hello Wo rld, o r rename the co mpilatio n unit
(file) to Hello Wo rld6 .java.
The .java file is called the source code fo r the class. Eclipse calls it the "co mpilatio n unit" because Java
co mpiles so urce files to co nvert pro grams into so mething the machine understands. We'll lo o k into the
co mpilatio n o f Java in greater detail in a future lesso n.
Fo r no w, do uble-click o n Re nam e t ype t o 'He llo Wo rld' to fix the name.

What About the Other One?


So what abo ut the o ther Applet we made? Ho w do es it wo rk? I'm happy yo u asked. We'll go o ver it no w, but
do n't panic if yo u do n't quite understand the explanatio n in this sectio n. By the end o f this co urse yo u will!
Open He llo Wo rld2 fro m yo ur java1_Le sso n0 1/src fo lder and turn o n line numbers as befo re:

OBSERVE:
1 import java.awt.*;
2 import javax.swing.*;
3
4 public class HelloWorld2 extends JApplet
5 {
6
public void init()
7
{
8
Container contentPane = getContentPane();
9
JLabel label = new JLabel("Hello Again, World!", SwingConstants.CENTE
R);
10
contentPane.add(label);
11
}
12 }
When we lo o k at the Applets resulting fro m these two classes, they lo o k similar, but the co de is very different.
As pro grammers, we cho o se fro m lo ts o f o ptio ns that determine ho w o ur co de will execute tasks. That's why
so me co de might lo o k abso lutely beautiful, but o ther co de might be nearly impo ssible to fo llo w. While yo ur
first prio rity when writing any co de is to make sure it wo rks po rperly, yo u also want to keep in mind that o ther
pro grammers will use and edit the co de yo u write. If yo ur o riginal co de isn't well-written, that can beco me a
real burden to o thers in the co mmunity. Write go o d co de in the first place, and make sure subsequent
pro grammers do n't curse yo ur name!
In this co urse, we want to instill principles o f go o d so ftware engineering, so that yo ur co de will run co rrectly,
lo o k beautiful, and be useful and clean fo r pro grammers who will use it in the future.
No w, as it turns o ut, the two Applets we wro te are bo th co mpo sed o f go o d, so lid co de. But they're just two o f
the many ways we co uld have written them. I'll sho w yo u ano ther o ne. In the He llo Wo rld2.java file, turn o n
the line numbers again (right-click the vertical bar left o f the Edito r windo w and select Sho w Line Num be rs).
Expand any co mpressed lines. If yo u have a blank line at the to p, remo ve that blank line. Here's ho w it wo rks:
OBSERVE:
1 import java.awt.*;
2 import javax.swing.*;
3
In the co de abo ve, the impo rts have an * (asterisk) at the end o f the package names. This tells Java that yo u
might want to use any o f the classes in the java.awt o r javax.swing packages. With the *, yo ur co de can then
use any class in the package. Java will retrieve the class at the same time, whether it used the impo rt with the
* o r the specific class name.
OBSERVE:
4 public class HelloWorld2 extends JApplet
5 {
The co de abo ve is a J Apple t ; o ur first was an Apple t . The J Apple t class is in the javax.swing package,
so we impo rted that package instead o f java.apple t .
OBSERVE:
6
7

public void init()


{

The co de abo ve is the initial definitio n o f the init () metho d.


OBSERVE:
8

Container contentPane = getContentPane();

The co de abo ve gets the Co nt aine r fro m the J Apple t instead o f fro m the Graphics area used in Apple t s.

OBSERVE:
9
R);

JLabel label = new JLabel("Hello Again, World!", SwingConstants.CENTE

The co de abo ve creates a JLabel and then writes "Hello Again, Wo rld!" o n the label, rather than into the
Graphics area.
OBSERVE:
10

contentPane.add(label);

The line abo ve adds the label to the Co ntainer fro m the JApplet.
OBSERVE:
11
12 }

The lines o f co de abo ve end the definitio n o f the init () metho d, then end the definitio n o f the He llo Wo rld2
class. No tice the indentatio n that enables yo u to see the matching braces mo re easily:
The line 7 { matches up with line 11's } and
the line 5 { matches up with line 12's } .
This indentatio n is no t required by Java, but it's go o d fo rm fo r pro gramming and allo ws better readability.
Tho ugh it may no t seem like it, the biggest difference between these two Applets is that o ne is an Apple t and
the o ther is a J Apple t . Bo th classes are Applets because J Apple t inherits fro m Apple t . We kno w this is
the case by checking in the API. Lo o k at the im po rt statements. They tell Java where to lo o k fo r the classes
that yo u didn't write, and it's also where you can find the same info rmatio n.
Clicking o n the to p left co rner o f any class's API page will sho w yo u the class's inheritance tree.
Go to the JApplet class in the API and check it o ut! The JApplet inheritance tree lo o ks like this:

This tells yo u that the class J Apple t inherits fro m the Apple t class,
which inherits fro m Pane l,
which inherits fro m Co nt aine r,
which inherits fro m Co m po ne nt ,
which inherits fro m Obje ct .
Everything lo cated above a specific class in an inheritance tree is referred to as the class's super o r ancestor
(the o ne directly abo ve it is referred to as its parent). Everything lo cated below a specific class in an
inheritance tree is referred to as the class's sub o r subclass (also referred to as the class's child).
So , J Apple t has a parent (o r super) o f Apple t , and Apple t has a subclass (o r child o f J Apple t .
In future lesso ns, we'll explo re the info rmatio n in the API in mo re detail.

Hierarchy Structure in Eclipse


Ano ther way to view the hierarchy o f classes is thro ugh the Eclipse hierarchy windo w.

Make sure yo u have He llo Wo rld2.java o pen in Eclipse. Highlight the wo rd J Apple t in line 4. Right-click it
and select Ope n T ype Hie rarchy fro m the po p-up menu:

A Hie rarchy tab appears where the Package Explo rer windo w used to be. It's the same inheritance hierarchy
tree that yo u saw in the API.

In the API yo u can see that every class inherits fro m the Obje ct class. This is the essence o f o bject-o riented
pro gramming.
Again, no te that the impo rts have * at the ends o f the package names. This tells Java that yo u might want to use any o f
the classes in the java.awt o r javax.swing packages. The * is used co mmo nly in Co mputer Science as a wildcard.
That means anything (that fits the circumstances) can replace it. In this case, the "circumstances" are that the package
must be java.awt o r javax.swingfo r example, impo rting java.awt .* means yo u can use any o bject fro m the
java.awt package.
But no te this exceptio n: package wildcards o nly wo rk fo r classes. Specifically, if yo u have two packages, say java.awt
and java.awt .e ve nt , im po rt java.awt .* do es not get all o f the classes in the package java.awt .e ve nt . Yo u wo uld
need to impo rt bo th java.awt .* and java.awt .e ve nt .* to get the classes fro m bo th packages.
Phew! That's it fo r this lesso n 2! Wait a sec, let Duke take a picture o f yo u to capture this mo ment o f acco mplishment!

Yo u're lo o king greatI can't wait to see yo u in the next lesso n!

Yo u're lo o king greatI can't wait to see yo u in the next lesso n!

Remember: o nce yo u finish the lesso n, go back to the syllabus page by clicking the Syllabus tab abo ve and co mplete
the Quiz(zes) and Pro ject(s).
Copyright 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Applets
When yo u co mplete this lesso n, yo u will be able to :

Lesson Objectives
get an image and sto re it in the image fo lder.
wo rk o n the Duke image
impo rt the Applet class.
use the wildcard and get the entire java.awt package.

Applets
We have already created and run a basic Applet. An Applet is a class that's pro vided fo r us by Java. All o bject-o riented
pro gramming depends o n classes. Specifically, we define Classe s o f Obje ct s so we can use them in o ur pro grams.
Pro grammers also create and define new classes fo r their o wn specific purpo ses. Still o ther classes are im po rt e d
fro m Java. Yo u can check o ut the vario us types o f class functio ns in the API. In this lesso n, we'll fo cus primarily o n the
mo st co mmo nly used Classes in JavaApple t s.

What Can Applets Do?


Our first Applet printed "Hello Wo rld." In Java, a string o f characters (In English, we wo uld identify tho se
characters as wo rds, phrases, o r sentences) is defined within a Java Class o f its o wn called the St ring
Class. We create St rings in Java using do uble quo tatio n marks: " T his is a st ring" . Whatever yo u put
inside the quo tatio n marks is quo ted exactly, beco ming the String. (This is the o nly place in Java
pro gramming where we can get away with a typo !)
So , in the paint () metho d o f o ur Hello Wo rld Applet, we to ld the Graphics Class (using g) to use metho ds
drawSt ring() and drawRe ct () to print a St ring ("Hello Wo rld") and draw a rectangle. Take a lo o k at
Hello Wo rld's paint () metho d:
OBSERVE:
g.drawString("Hello World!", 5, 15); // put String "Hello World" at (x,y) loc
ation of (5,15)
and
g.drawRect(0, 0, 100, 100);
// drew a Rectangle with top-left corner at (0,0)
with width and height of 100
So , what else can Applets do ? Let's create a new Eclipse pro ject and find o ut.
Generally, pro grammers put their co de into so urce (src) fo lders, so Eclipse makes src fo lders fo r each Java
pro ject to o . Go ahead and create an Eclipse pro ject to ho ld yo ur classes fo r java1_Le sso n0 3. We did this
befo re in Lesso n 1, but in case yo u need a little help remembering ho w, fo llo w these steps:
Select File | Ne w | J ava Pro je ct :

In the New Java Pro ject windo w, name yo ur pro ject java1_Le sso n0 3, add it to the J ava1_Le sso ns wo rking
set, and click Finish:

If yo u see the o ptio n to "Open Asso ciated Perspective," check the Re m e m be r m y de cisio n bo x and then
click No . We want to keep o ur o wn perspective enviro nment.

If yo u fo rget to click No and yo ur windo w go es crazy, remember yo u always have yo ur "panic butto n":

This butto n will always bring yo u back to the pro per perspective.
Yo u sho uld see java1_Le sso n0 3 in yo ur Package Explo rer Windo w.
No w, make a new Java Class in the java1_Lesso n0 3 pro ject file.
1. Select java1_Le sso n0 3 in the Package Explo rer so it's highlighted.
2. Right-click java1_Le sso n0 3 in the Package Explo rer, o r select File fro m the Eclipse Menu, and
then cho o se Ne w | Class.
3. Name it MyFirst Duke , make the Superclass java.apple t .Apple t , and click Finish.
Yo u'll see this co de in yo ur Edito r wo rkspace windo w:

Because yo u specified that the Superclass was java.apple t .Apple t , the Eclipse code generator perfo rmed
these helpful tasks fo r yo u:
impo rted java.applet.Applet
extended Applet
No w, type the MyFirst Duke java Class as sho wn:
CODE TO TYPE:
import java.applet.Applet;
import java.awt.*;
public class MyFirstDuke extends Applet {
public void paint(Graphics graph) {
Image action = getImage(getDocumentBase(),"../../images/duke/dukeWave.gi
f");
graph.drawImage(action, 10, 10, Color.white, this);
graph.drawString("I am a waving duke", 10, 130);
}
}
Save and run it.

Oo ps!
Hey, wait a minute! We to ld Java to get an image and draw itwe see "I am a waving Duke," but no Duke! Why
can't we see the image?

So metimes Java will tell us abo ut erro rs, and so metimes we have to catch them o urselves. Usually if Java
can run the co de, it will. (Fo r example, Java cannot run specific co de if it's unable to find a Java class that yo u
to ld it to use.) In this situatio n, Java did what it co uld, but it didn't draw the image we to ld it to , because it was
unable to find it. Java pro bably co uldn't find it because I hadn't given it to yo u yet.

Getting Images
Let me give that image to yo u no w. Click here to get the image files yo u'll need fo r this lesso n. When
pro mpted fo r a wo rking set, select J ava1_Le sso ns.
No w yo u have an /im age s fo lder that yo u can use fo r the entire co urse. It sho uld be listed under
Java1_Lesso ns with yo ur java1_Lesso n0 1 and java1_Lesso n0 3 pro jects in the Package Explo rer view.
Open the /im age s fo lder to see the /duke subfo lder co ntaining the images.
Go back to yo ur java1_Lesso n0 3 Pro ject and click o n MyFirst Duke .java (in the default package).
Run the MyFirst Duke Applet againright-click MyFirst Duke .java and select Run As | J ava
Apple t .
No w yo u'll see this:

Ahh, much better! No w, lo o k at the co de. No tice that the co mpiler finds the image using the fo llo wing line:
OBSERVE:
Image action = getImage(getDocumentBase(),"../../images/duke/dukeWave.gif");
The t wo do t s are impo rtant. We need to direct Java to the right place. Each pair o f do ts tells Java to go up
o ne directo ry. So Java go es up t wo dire ct o rie s to java1_Le sso n0 3 and the main J ava1_Le sso ns, then
do wn thro ugh the /im age s and /duke directo ries, to the duke Wave .gif file.
Fo llo w the numbers 1 thro ugh 6 o n this chart to see ho w Java finds the image fro m the MyFirstDuke.java
class:

No w suppo se yo u want to keep yo ur duke images with yo ur java1_Lesso n0 3 pro ject. Let's try do ing that:
1. Go to the java1_Le sso n0 3/src fo lder and right-click it to see the po pup menu.
2. Cho o se Ne w | Fo lde r.
3. Name it im age s.
4. Click Finish.

1. Right-click the new /im age s fo lder to see the po pup menu.
2. Cho o se Ne w | Fo lde r (no tice again, I said Fo lde r).
3. Name it duke .
4. Click Finish.

Yo u'll see im age s.duke . And no w to make the co py:


1. Go to the im age s fo lder that we o riginally do wnlo aded, then go into the duke subfo lder.
2. Right-click o n duke Wave .gif and cho o se Co py.
3. Right-click yo ur new im age s.duke fo lder and cho o se Past e .
Yo u'll see the co py no w. Finally, get rid o f the do ts by giving the new path to the file yo u just placed:
CODE TO TYPE:
import java.applet.Applet;
import java.awt.*;
public class MyFirstDuke extends Applet {
public void paint(Graphics graph) {
Image action = getImage(getDocumentBase(),"images/duke/dukeWave.gif");
graph.drawImage(action, 10, 10, Color.white, this);
graph.drawString("I am a waving duke", 10,130);
}
}

Save and run it.

Applet Uses Other Classes


There are a few mo re interesting characteristics fo r us to explo re in the Class. Open yo ur MyFirst Duke .java file in the
Package Explo rer, if it's no t already o pen.
In an earlier lesso n, we learned that every class inherits fro m the Class Obje ct . We also learned that we had to impo rt
packages so Java co uld find classes. Ano ther impo rtant accepted practice o r convention when using Classes is that
they always begin with capital letters.
Lo o k thro ugh the MyFirst Duke co de in the Edito r Wo rkspace fo r wo rds beginning with capital letters:
OBSERVE:
import java.applet.Applet;
import java.awt.*;
public class MyFirstDuke extends Applet {
public void paint(Graphics graph) {
Image action = getImage(getDocumentBase(),"../../images/duke/dukeWave.gif");
graph.drawImage(action, 10, 10, Color.white, this);
graph.drawString("I am a waving duke", 10,130);
}
}
Okay, we cheated. drawSt ring do es no t begin with a capital letter, but it is using the St ring class.
We learned earlier that Java will no t run if it canno t find the Classes it needs. We to ld the MyFirst Duke class to
im po rt the Apple t class and we are writing the MyFirst Duke class in the co de, so Java can see them. We saw that
the Graphics class was impo rted if we used the wildcard impo rt o f java.awt .*.
So , what abo ut Im age and Co lo r and St ring? Where are we impo rting them?
What if we specifically say im po rt java.awt .Graphics?
CODE TO TYPE:
import java.applet.Applet;
import java.awt.Graphics;
public class MyFirstDuke extends Applet {
public void paint(Graphics graph) {
Image action = getImage(getDocumentBase(),"../../images/duke/dukeWave.gif");
graph.drawImage(action, 10, 10, Color.white, this);
graph.drawString("I am a waving duke", 10,130);
}
}
Remember, if yo u see
click o n the encircled + sign.
Do yo u see the

or

in the impo rts,

and the wavy lines (/\/\/\/\) under Im age and Co lo r?

Put yo ur mo use o ver the

. It says that Im age canno t be re so lve d t o a t ype and Co lo r canno t be re so lve d.

Mo dify the impo rt sectio n as sho wn:

CODE TO TYPE:
import java.applet.Applet;
import java.awt.Image;
public class MyFirstDuke extends Applet {
public void paint(Graphics graph) {
Image action = getImage(getDocumentBase(),"../../images/duke/dukeWave.gif");
graph.drawImage(action, 10, 10, Color.white, this);
graph.drawString("I am a waving duke", 10,130);
}
}
No w the erro rs are o n Graphics and Co lo r. Do yo u kno w what to do and the reaso n behind that so lutio n?
Mo dify the impo rt sectio n as sho wn:
CODE TO TYPE:
import
import
import
import

java.applet.Applet;
java.awt.Color;
java.awt.Graphics;
java.awt.Image;

public class MyFirstDuke extends Applet {


public void paint(Graphics graph) {
Image action = getImage(getDocumentBase(),"../../images/duke/dukeWave.gif");
graph.drawImage(action, 10, 10, Color.white, this);
graph.drawString("I am a waving duke", 10,130);
}
}
Ahh. All is well again. But it's easier to use the wildcard and get the entire java.awt package!
Let's give it a try just to make sure:
See the API fo r the java.awt package.
Scro ll do wn to the Class Sum m ary. (There are a lo t o f classes there.) Then, scro ll do wn to see that the package
specifically co ntains the Co lo r, Graphics, and Im age classes.
The wildcard (*) can be very handy.
Finally, let's go o ver the St ring. There's o ne special package that yo u never need to impo rt. Java impo rts it by default.
That package is java.lang. The class St ring is in the API in java.lang. Let's take a lo o k at it.
Go to the to p-level API page. No tice this is the to p-level API page to all o f the packages (Header o f Package s).
Scro ll do wn to the java.lang package and click it. Then, scro ll do wn to the Class Sum m ary and find the St ring class.

T ip

Classes in the java.lang package do no t need to be impo rted.

As yo u scro lled do wn, yo u may have no ticed the Syst e m class as well (it's just belo w the St ring class). This may
help yo u to see why the java.lang package do esn't need to be impo rted. The Syst e m class will always be needed
behind the scenes.
When pro gramming with Java, the API will be yo ur mo st useful to o l, so definitely get friendly with it!
In the next lesso n, we'll experiment with o ur MyFirst Duke class to see ho w Applets wo rk. See yo u there!
Copyright 1998-2014 O'Reilly Media, Inc.

Copyright 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

An Applet's Life Cycle


When yo u co mplete this lesso n, yo u will be able to :

Lesson Objectives
describe the life cycle o f an Applet.
create o r o verride metho ds in an Applet.
encapsulate task into metho ds.

Applets Continued
In this lesso n, we're go ing to examine the life cycle o f an Applet. We're also go ing to start encapsulating tasks into
metho ds we create o urselves, instead o f putting all o f them into the paint() metho d.

Applet Life Cycle


Let's get familiar with the Applet's life cycle. Applets are bo rn, they live fulfilling lives, and then they die. In this
lesso n, we'll delve into this cyber-miracle mo re deeply.
Every time yo u o pen an Applet, yo u're o pening an instance, o r object, fro m the Apple t class. I kno w, I keep
repeating this, but I will spare no redundancy if it helps yo u get this stuff do wn! Hence we'll address o bjects in
still greater detail in future lesso ns. But in this lesso n, we want to lo o k at instances by o bserving an Applet's
life cycle.
In o rder to create a new Applet, we write a class that extends the pre-existing Apple t class. Yo ur newly
defined Java class will be a subclass o f Apple t and thus will inherit all o f its capabilities. When yo ur Applet
lo ads (because yo u tell it to run), here's what happens:
An instance o f yo ur Applet's class is created.
The Applet initializes itself.
The Applet starts running.
To get a visual representatio n o f this pro cess, we'll inco rpo rate mo re images. Since we already have an
/im age s fo lder, let's use the images in it fo r this lesso n as well.
We'll start o ut by making an applet that did the same thing as the applet in the last lesso n, but this time we'll
mo ve so me o f the tasks that we put inside the paint() metho d into ano ther metho d. This will be o ur first
attempt at mo dularity, which is a fancy wo rd fo r making things mo re useful to o ther pro grams.
Make a new pro ject fo r Lesso n 4, and name it java1_Le sso n0 4 . Make a new Class in this pro ject named
MySe co ndDuke (remember to name the Superclass java.apple t .Apple t ). No w let's pro gram!

CODE TO TYPE:
import java.applet.Applet;
import java.awt.*;
public class MySecondDuke extends Applet{
public void init(){
setBackground(Color.pink);
}
public void paint(Graphics g) {
Image action = think(g);
// get the action image for Duke
g.drawImage(action, 10, 10, Color.white, this);
}
public Image think(Graphics graph){
graph.drawString("I am a thinking Duke", 10,130);
Image myAction = getImage(getDocumentBase(),"../../images/duke/thinking.
gif");
return myAction;
}
}
Save and run it.
Let's break do wn this co de to see what's go ing o n here:
OBSERVE:
import java.applet.Applet;
import java.awt.*;
public class MySecondDuke extends Applet{
public void init(){
setBackground(Color.pink);
}
public void paint(Graphics g) {
Image action = think(g);
// get the action image for Duke
g.drawImage(action, 10, 10, Color.white, this);
}
public Image think(Graphics graph){
graph.drawString("I am a thinking Duke", 10,130);
Image myAction = getImage(getDocumentBase(),"../../images/duke/thinking.
gif");
return myAction;
}
}
We're overriding the init () metho d fro m the Applet class and the paint () metho d fro m
java.awt.co ntainer.paint. We've also made a new metho d called t hink(), which isn't o verriding any metho ds
fro m a superclass. It's called inside o f the paint() metho d, it prints "I am a thinking Duke" to the screen and
uses the ge t Im age () metho d to grab the image "../../images/duke/thinking.gif." Then the graphics o bject
draws that graphic to the screen via the g.drawIm age () metho d. No tice we sto red the image in a variable
named act io n, which is o f variable type Im age . Then the t hink() metho d returns the actio n using re t urn
m yAct io n. Fo llo w the arro ws belo w to see a visual representatio n:

The Graphics Object we named g gets picked up by the t hink(g) metho d, which renames the o bject graph in
the metho d definitio n. The Graphics o bject graph then uses its drawString() metho d to write "I am a thinking
duke." Inside the definitio n o f the think() metho d, we sto re the variable called m yAct io n. And inside o f the
variable myActio n is an image called thinking.gif. The t hink() metho d returns the image to paint (), which
sto res it in act io n. The Graphics o bject g inside the paint() metho d has a metho d named drawImage().
drawimage() draws the co ntents o f the variable act io n which is the dukewave.gif image. Go t it? Go o d.
See the API fo r the metho ds available to the Graphics o bject.
No w let's get back to the Applet's life cycle. When yo u e xit the Applet, it sto ps and if necessary, Java will do a
"cleanup." Cleanup includes things like clo sing files and remo ving unnecessary memo ry access. Befo re
Java, pro grammers had to do this tedio us cleanup wo rk every time they wro te a pro gram. The main steps in
an Applet life cycle are:
Initialize itself.
Start running.
Stop running.
Perfo rm a final cleanup, in preparatio n fo r being unlo aded (destroyed).
Go to the Applet page, scro ll do wn to the Me t ho d Sum m ary, and lo o k fo r metho ds (the seco nd co lumn
has metho d names):
destro y()
init()
start()
sto p()
These metho ds are a built-in part o f the Applet class and yo u inherit them when yo u e xt e nd Apple t .
As creato r o r implementer o f a new Class, yo u can override the parents just as we did with
MySe co ndDuke .java and all o f the classes we've written so far. This means that when yo u write a metho d in
your co de with the same name as a metho d o f its parent (o r any o ther superclass), the o ne that you wro te is
the o ne that Java will use instead o f the o ne in the parent. Java will use the most specific metho dthat is, the
o ne farthest do wn in the Applet's hierarchical family tree. In yo ur pro gram, yo u've actually o verridden the
init () metho d by making yo ur o wn metho d. Try remo ving the init metho d and see what happens. Yo ur
pro gram sho uld still wo rk, but yo u wo n't see the nice sho cking pink backgro und anymo re.

Note

When yo u o verride a metho d, yo u're using o ne o f the majo r capabilities o f o bject-o riented
pro gramming, polymorphism. Poly (mo re than o ne; many) and morphism (the co nditio n o f having
a specified fo rm)in co mputer languages, this means that the same name can be used in
different places with different meanings. Altho ugh initially this can be co nfusing, ultimately it's a
very useful trait. Trust me.

No te that in o ur earlier Applets, we did no t have an init () metho d, but in this o ne we do .

Lo o k at yo ur MySeco ndDuke class in the Wo rkspace. See the

ico ns in the left co lumn?

Mo ve yo ur mo use o ver tho se ico ns yo u see at the init() and the paint() metho ds. They tell yo u exactly which
o f the superclasses has implemented the metho d befo re. So whose co de are yo u o verriding?

Hmm, init () says we are o verriding java.apple t .Apple t .init , as we wo uld expect, since we inherit fro m
Apple t but paint () says we are o verriding java.awt .Co nt aine r.paint .
Let's lo o k at o ur Applet's ancestral trail to learn mo re. Do an o pe n t ype hie rarchy o n the Applet. Highlight
the wo rd Apple t , then right-click it and select Ope n t ype hie rarchy.

Yo u'll see the fo llo wing o n the left:

No tice that in the hierarchy tree (yo u might have to scro ll up a bit), Co nt aine r is a supe rclass o f Apple t and
hence is a supe rclass o f any class that e xt e nds Apple t .
So , even tho ugh we had no t written an init () metho d earlier, we had one by default because o ur Applet
inherits the default init () fro m the parent Applet class.
Find and click the Applet class (lo o k fo r the wo rd Applet in the left co lumn). Yo u sho uld see so mething like
this:

In the Applet class, scro ll do wn to the init () metho d and click its link.
Yo u'll see (near the bo tto m o f the descriptio n) a mo re detailed descriptio n o f the metho d:
"The implementatio n o f this metho d pro vided by the Applet class do es no thing." Huh.
This must be the reaso n we didn't see anything special in o ur previo us Applets. No t every Applet has to
o verride every metho d. In fact, so me very simple Applets (like o ur He llo Wo rld) o verride no metho ds at all.
Later we'll add mo re graphical user interface co mpo nents to o ur Applets in the init () metho d.
So what abo ut that paint () metho d? Ho w and when do es it get started?
Well, after the Applet has co mpleted initializatio n, it displays itself o nscreen in the Graphics area o f the Applet
thro ugh the paint () metho d.
The paint () metho d is in the Co nt aine r class, so lo o k in that class fo r info rmatio n abo ut it in the API. Since
Co nt aine r is a supe rclass o f Apple t , we have a link to it thro ugh the Applet class's hierarchy at the to p o f
its API page.
At the to p o f the Applet API page, click o n the link to the Co nt aine r class in the Applet's hierarchy. Scro ll
do wn under the Me t ho d Sum m ary pro vided in the Applet class. No tice the additio nal frames sho wing all o f
the metho ds that the Applet class inherits and fro m who m they inherit.

Any class that extends Applet gets the metho ds defined in the Applet class, and all o f tho se metho ds defined
in Applet's superclasses. This trait o f o bject-o riented languages is called modularization.
This page pro bably has mo re info rmatio n than we need no w, but it is go o d to kno w ho w to fo llo w related
links.
Go back to the Applet class page, scro ll do wn to the Metho ds inherited fro m class java.awt.Co ntainer frame,
and click o n the paint () metho d link there. .
Again, this is mo re info rmatio n than we need at the mo ment, but no tice that the metho d is passed a Graphics
o bject o n which to paint .
We do n't paint o n the Applet, we paint o n this Graphics area. One o f the things that the Applet do es upo n
initializatio n is create this Graphics area to give to us in the paint() metho d. Once the metho d is used, we can
access this Graphics o bject via the instance o f it that is passed to us.

Lo o k at the co de fo r MySe co ndDuke .java. No tice the first line o f the paint (Graphics g) metho d. No w lo o k
at MyFirst Duke .java (in java1_Lesso n0 3). No tice the first line o f the paint (Graphics graph) metho d there.
No w, lo o k at the paint metho d specificatio n in the API fo r Co nt aine r: public vo id paint(Graphics g).

Note

In all three metho ds abo ve, Graphics appears first because the metho d must pass a Graphics
o bje ct . This specificatio n tells us the t ype o f Object needed.
Yo u can give whatever name yo u like to the instance o f the Graphics o bject that is passed, as
lo ng as the same name is used thro ugho ut the blo ck o f co de within braces.

Hence o ne class may call the Graphics o bject g, while ano ther might call it graph. This is ano ther nice thing
abo ut modularity. Yo u do n't have to wo rry abo ut the name so me o ther pro grammer gives to an o bject. Within
yo ur o wn co de, variable names are local, meaning yo ur names will o nly be seen by the co de that co ntains
them.
Open yo ur MySe co ndDuke .java file in the Edito r, if it's no t still o pen. Edit it as sho wn:
CODE TO TYPE:
import java.applet.Applet;
import java.awt.*;
public class MySecondDuke extends Applet{
public void init(){
setBackground(Color.pink);
}
public void paint(Graphics graph) {
Image action = think(g);
// get the action image for Duke
g.drawImage(action, 10, 10, Color.white, this);
}
public Image think(Graphics graph){
graph.drawString("I am a thinking Duke", 10,130);
Image action = getImage(getDocumentBase(),"../../images/duke/thinking.gi
f");
return action;
}
}
It lo o ks like we have so me erro rs to co nsider.

If yo u mo ve yo ur mo use o ver the erro r symbo ls, they bo th say "g canno t be reso lved."
To fix it, change the underlined gs to graph in the paint () metho d.
(Yo u co uld also change the co de back to the way it was initiallyJava will accept either fix.)
Save and run it, just to make sure everything still wo rks.

Phew! I'm glad we fixed that. The issue there was o ne o f consistency. When we changed the parameter to
"graph," Java didn't kno w what "g" represented anymo re. No tice, ho wever, that the blo ck o f co de defined fo r
public Im age t hink(Graphics graph){ can specify whatever variable name we want. The { } (braces)
designate the scope within which a variable name is kno wn. In o ther wo rds, o ther parts o f the pro gram kno w
no thing abo ut g because g is inside the paint() metho d's sco pe { }, which is inside o f the rest o f the pro gram.
And o f co urse, the paint metho d do es what it says: it paints.
Once the Applet is initialized, the Applet executes the start() metho d and any o ther metho ds yo u've written.

Note

When yo u draw so mething after the start o f the Applet, use the metho d re paint () rather than
paint . re paint () will clear the screen and then call the paint metho d so that it do esn't paint o ver
previo us material.

Adding Methods
Let's wo rk o n an Applet that has mo re capabilities and learn mo re abo ut the Applet life cycle. There were three actio ns
fo r Duke in MySe co ndDuke .java. Two o f them, init () and paint (Graphics g), were inherited Apple t metho ds. We
made the third metho d, t hink(Graphics graph), fro m scratch, specifically fo r o ur Duke Applet.
This is ano ther example o f mo dularity and go o d pro gramming practice. We changed MyFirst Duke (which sto red all o f
its tasks in the paint metho d) into a pro gram with separate metho ds fo r separate actio ns. By inco rpo rating this
mo dularity to metho ds, we increase o ur pro gram's flexibility.

Control
While so me things (metho ds, o bjects, attributes) are inherited fro m the Applet, you have the po wer to co ntro l
the actio n o f the Applet as well.
In MySe co ndDuke .java--> No w, we'll make a new class that defines mo re actio ns and hence allo w Duke to
do mo re stuff. Do n't wo rry if yo u do n't understand all o f the co de being used in this Applet. We'll explain it all
later.
In yo ur java1_Le sso n0 4 /src fo lder, create a new class named Duke , with the Superclass
java.apple t .Apple t .
Type the fo llo wing into Duke .java:

CODE TO TYPE:
import java.applet.Applet;
import java.awt.*;
public class Duke extends Applet {
int test = 0;
Image action;
public void paint(Graphics g) {
switch (test%3) {
case 0: action= this.write(g); break;
case 1: action= this.think(g); break;
case 2: action= this.wave(g); break;
}
g.drawImage(action, 10, 10, Color.white, this);
test = test + 1;
// Show that Restart repaints to make a new action
}
public Image write(Graphics graph) {
graph.drawString("I am a writing Duke", 10, 130);
Image myAction = getImage(getDocumentBase(),"../../images/duke/penduke.g
if");
return myAction;
}
public Image think(Graphics graph) {
graph.drawString("I am a thinking Duke", 10, 130);
Image myAction = getImage(getDocumentBase(),"../../images/duke/thinking.
gif");
return myAction;
}
public Image wave(Graphics graph) {
graph.drawString("I am a waving Duke", 10, 130);
Image myAction = getImage(getDocumentBase(),"../../images/duke/dukeWave.
gif");
return myAction;
}
}
Befo re we run it, let's take a clo ser lo o k at the co de:

OBSERVE:
import java.applet.Applet;
import java.awt.*;
public class Duke extends Applet {
int test = 0;
Image action;
public void paint(Graphics g) {
switch (test%3) {
case 0: action= this.write(g); break;
case 1: action= this.think(g); break;
case 2: action= this.wave(g); break;
}
g.drawImage(action, 10, 10, Color.white, this);
test = test + 1;
// Show that Restart repaints to make a new action
}
public Image write(Graphics graph){
graph.drawString("I am a writing Duke", 10,130);
Image myAction = getImage(getDocumentBase(),"../../images/duke/penduke.g
if");
return myAction;
}
public Image think(Graphics graph){
graph.drawString("I am a thinking Duke", 10,130);
Image myAction = getImage(getDocumentBase(),"../../images/duke/thinking.
gif");
return myAction;
}
public Image wave(Graphics graph){
graph.drawString("I am a waving Duke", 10,130);
Image myAction = getImage(getDocumentBase(),"../../images/duke/dukeWave.
gif");
return myAction;
}
}
Essentially, this Applet wo rks like the o ne we did befo re, except no w we have three metho ds instead o f o ne.
We also added a swit ch statement that takes an integer named t e st (we kno w it's an integer because we
declared it using int t e st = 0 ;. We mo d o ut by 3 using test%3 (reads "test mo d 3"). "Mo d o ut" means to take
the remainder. In this case, it means to divide by 3 and take the remainder, so 5%3 = 5/3 = (1 with remainder 2)
= 2. Then the switch statement gets 0 , 1, o r 2 successivelyif it's 0 , it calls the writ e () metho d, and so o n.
Save and run it.

Watching a Life
In the life-cycle o f an Applet, we see that it is initialized o nly o nce. So lo gically, the init () metho d wo uld be run
o nly o ne time as well. Ho wever, Applets are usually seen in bro wsers. When the user leaves the pagefo r
example, to go to ano ther pagethe bro wser sto ps and destro ys the applet. The state o f the applet is no t
preserved. When the user returns to the page, the bro wser intializes and starts a new instance o f the applet.
Similarly, when ano ther windo w o n the co mputer co vers the Applet, the Applet must be repainted when it's
fully unco vered again. When the Applet is started again, the st art () and paint (Graphics g) metho ds (via
re paint ()) are called.
Lo o k fo r the first actio n (the o ne yo u see no w) o n the list that we have in o ur paint metho d. No tice what's next.
In o ur co de, we made it so that each time the Applet is Restarted (and hence repainted), Duke's activity will
change in a specific o rder.
Click Apple t (in the upper left co rner) and select Re st art . No tice Duke's actio n and its lo catio n o n the list.
Click Apple t | Re st art again and o bserve the change.
Do it again.
The actio ns go in the sequence listed.
No w, no te so me o ther aspects o f the applet's life-cycle:
Select Apple t | St o p (no te activitysho uld be empty).
Select Apple t | St art (no te activitysho uld be next in sequence).
Select Apple t | St o p (no te activitysho uld be empty).
Select Apple t | Re st art (no te activitysho uld be next in sequence).
Keep the applet o pen fo r no w.
No w, we'll Re st o re Do wn the lesso n windo w so we can see the Appletview "behind" it. Click the Re st o re
Do wn ico n at the upper right o f the lesso n windo w:

Minim ize the Appletviewer windo w:

No w get it back by clicking its Re st o re Up ico n (no te the activityit sho uld be updatedsho wing next in
sequence).
No w let's o pen ano ther instance! No tice Duke's actio n and its lo catio n o n the list. Mo ve the Appletviewer to
the right so we can launch a new instance o f the Applet and yo u can still see it and this lesso n.
Click in the edito r windo w and run the applet again. Yo u no w have two Appletviewers running. Yo u can run
as many applets as yo u need in this fashio n.
Restart the first o ne (no te activitysho uld be next in sequence). Seco nd applet do es no t change.
Restart o n the seco nd o ne (no te activitysho uld be next in sequence). First applet do es no t change.
Sto p o n the seco nd o ne (no te activitysho uld be empty). First applet do es no t change.
Each time yo u run a new Applet, yo u get exactly thata new instance o f an Applet. Later lesso ns will illustrate
this further and pro vide mo re info rmatio n abo ut writing Classe s.
Fo r mo re o n the Applet life cycle, see the Oracle Tuto rial.
Co ngratulatio ns! Yo ur Java skills are getting stro nger and stro nger.

Copyright 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Decisions, Decisions, Decisions


When yo u co mplete this lesso n, yo u will be able to :

Lesson Objectives
use if statements in yo ur pro gram.
use switch statements in yo ur pro gram.
use co pariso n o perato rs.

Program Control Using If Statements


All algo rithms are made up o f the fo llo wing control co nstructs, which direct the flo w o f the pro gram:
sequences (assignment statements, IO calls)
repetitio ns/lo o ps (while, fo r, do )
decisio ns/selectio ns (if/then, switch)
metho d invo catio n
This lesso n fo cuses specifically o n co ntro l given decision statements (so metimes called conditionals). There are two
types o f decisio n statements:
if statements
switch statements
We actually used a switch statement in the last lesso n, and we'll co ver them again here. But first, let's discuss if
statements:

If Statements
An if statement co nsists o f three majo r parts:
OBSERVE:
if (boolean)
{
statements
}
else
{
statements
}
the if : the co nditio n being tested (inside parentheses) must result in a booleana fancy wo rd fo r
"true o r false."
the st at e m e nt (s) to be executed: if the co nditio n is t rue no tice Java do es not use the keywo rd
t he n (it is implied).
the e lse : (o ptio nal) if present, the st at e m e nt (s) that fo llo w it are executed if the co nditio n is
f alse .

Note

Java uses parentheses ( ) fo r:


- co nditio ns in decisio n statements (if and swit ch).
- fo rmal and actual metho d parameters.
- precedence in math and lo gic expressio ns.

Here is an example o f the syntax used when o nly o ne statement is to be perfo rmed. In this example,
st at e m e nt 1 is executed if the co ndit io n is true, OR st at e m e nt 2 is executed if the co ndit io n is false. If,
after the if o r e lse , there is o nly one statement to execute, no braces {} are needed aro und the statement.

OBSERVE:
if (condition)
statement1;
else
statement2;
Belo w is a flow chart illustrating the flo w o f co ntro l after an if statement. Inside the diamo nd-shaped figure, a
questio n is asked. Depending o n whether the answer to the questio n is f alse o r t rue , co ntro l will go to the
left o r right respectively. (The rectangles indicate executio n statements in the co de.) When either o ne o f these
is co mpleted, co ntro l will then co ntinue sequentially do wn the remaining co de statements.

The "Statements" in the flo w chart abo ve co uld also be blocks o f statements:

Fo r the remainder o f this lesso n, after if statements, we'll assume they are single statements o r blo cks o f
statements (in braces). The braces indicate a block, that is, that mo re than o ne statement needs to be
executed.

Note

Java st at e m e nt s end in semi-co lo ns (;). There is no ; after a blo ck. The blo ck simply gro ups
the statements within it.

An e lse statement may no t even be needed, so a decisio n might lo o k like this:

OBSERVE:
if (condition)
statement1;
Remember that spaces and blank lines mean no thing to Java, so the previo us co de co uld also be written as
a o ne-liner:
OBSERVE:
if (condition) statement1;
Tho se two statements are equivalent and hence bo th have the same flo w chart:

Okay, no w let's try an example.


Make a new pro ject in the J ava1_Le sso ns wo rking set named java1_Le sso n0 5 . Make a new class fo r this
pro ject named T e st Apple t that extends java.applet.Applet (i.e. the SuperClass is java.applet.Applet). Type in
the co de belo w:
CODE TO TYPE:
import java.applet.Applet;
import java.awt.*;
public class TestApplet extends Applet {
public void paint (Graphics g) {
int myNumber = 1;
if (myNumber == 1)
{
g.drawString("My number matches",10,20);
}
}
}
Save and run it.
In the paint ( ) metho d, we set the variable m yNum be r to 1. Then we asked if myNumber was equal to 1 in
the co nditio n o f the if statement (myNumber == 1). In java, like in o ther languages, checking "is equal to " is
do ne using two equals signs ==. A single equals sign = is used to assign values to variables. In this case,
since "1 == 1" is t rue , the statement g.drawString("My number matches", 10 ,10 ); was executed and we saw
"My number matches" printed to the screen.
Try changing m yNum be r = 0 and then run it again. This time it sho uldn't print anything.
No w let's try this:

CODE TO TYPE:
import java.applet.Applet;
import java.awt.*;
public class TestApplet extends Applet {
public void paint (Graphics g) {
int myNumber = 0;
if (myNumber == 1)
{
g.drawString("My number matches",10,20);
}
else {
g.drawString("My number doesn't match",10,20);
}
}
}
Save and run it. This time, "My number do esn't match" prints.
No w, try this:
CODE TO TYPE:
import java.applet.Applet;
import java.awt.*;
public class TestApplet extends Applet {
public void paint (Graphics g) {
int myNumber = 0;
if (myNumber == 1);
{
g.drawString("My number matches",10,20);
}
else {
g.drawString("My number doesn't match",10,20);
}
}
}
Save it. No te the wo rd e lse has a wavy underline and a red X in the left co lumn.
When yo u mo ve the mo use o ver the e lse erro r, yo u see the descriptio n Synt ax e rro r o n t o ke n " e lse " ,
de le t e t his t o ke n. Since we added a ; at the end o f the if line, it thinks the e lse is there witho ut an if .
And actually, if yo u remo ve the e lse , the erro r will go away. Try it. Yo u'll get a "lo gical erro r" which means it
wo n't wo rk the way yo u intended, but Java wo n't "yell" at yo u because, syntactically, it's o kay to end the if
statement witho ut do ing anything. A semi-co lo n ; simply ends a statement. It seems a bit o dd because it
wo n't actually DO anything, but it's o kay acco rding to Java.

T ip

This may seem kind o f o bvio us, but when yo u get erro rs, o nly fo llo w the suggestio n if it makes
sense. Otherwise, lo o k at yo ur co de until it does make sense befo re changing things!

Remo ve the ; so the line reads if (myNumber == 1) and save the pro gram.

Placement of Block Braces


Indentatio ns and new lines mean no thing to Java. Pro grammers use them to help make their co de easier to

read. Semico lo ns, parentheses, and brackets make it po ssible fo r Java to read o ur co de.
Let's lo o k at so me mo re examples.
Make a new Class in yo ur java1_Le sso n0 5 pro ject named Driving that extends java.applet.Applet.
CODE TO TYPE:
import java.applet.Applet;
import java.awt.*;
public class Driving extends Applet {
int age = 15;
public void paint(Graphics g) {
if (age > 15)
g.drawString("Age is " + age, 50, 50);
g.drawString ("You may drive", 50, 70);
}
}
Save and run it. No w try so me different ages to see what happens.

WARNING

Befo re driving a mo to r vehicle, check the laws in yo ur state!

Because the g.drawSt ring(" Yo u m ay drive " , 5 0 , 7 0 ); line in the paint ( ) metho d is no t within an e lse o r
within a blo ck defined by { and } fo r the if statement, it always prints. But is that what we meant to happen? We
want the if statement to determine whether we are o ld eno ugh to drive o r no t and that sho uld depend o n the
value sto red in age .
No tice again that indentatio n do es no t matter to Java. Java is interested o nly in the placement o f the braces.
Add braces as sho wn belo w:
CODE TO TYPE:
import java.applet.Applet;
import java.awt.*;
public class Driving extends Applet {
int age = 15;
public void paint(Graphics g) {
if (age >15)
{
g.drawString("Age is " + age, 50, 50);
g.drawString ("You may drive", 50, 70);
}
}
}
Save and run it.
Try so me o ther numbers by changing the value o f the age variable. (Later in this co urse we'll take input fro m a
user and then change the value o f variables like age acco rdingly )
Let's make it so no matter what age we put into the age variable, we'll get the right o utput.

CODE TO TYPE:
import java.applet.Applet;
import java.awt.*;
public class Driving extends Applet {
int age = 15;
public void paint(Graphics g) {
if (age > 15)
{
g.drawString ("Congratulations!", 50, 50);
g.drawString ("You may drive", 50, 70);
}
else
{
g.drawString ("Wait!", 50, 50);
g.drawString ("You may not drive yet", 50, 70);
}
g.drawString("Age is " + age, 50, 90);
}
}
Run it.
No w, yo u might be wo ndering if we can simply get rid o f e lse and instead just use a sequence o f if
statements. Let's give it a try.
CODE TO TYPE:
import java.applet.Applet;
import java.awt.*;
public class Driving extends Applet {
int age = 15;
public void paint(Graphics g) {
if (age > 15)
{
g.drawString ("Congratulations", 50, 50);
g.drawString ("You may drive", 50, 70);
}
if (age < 15)
{
g.drawString ("Wait a few years", 50, 50);
g.drawString ("You may not drive yet", 50, 70);
}
g.drawString("Age is " + age, 50, 90);
}
}
Save and run it. What happened? It's an easy mistake to make.
If yo u have two if s, and yo u're using less than and greater than signs, make sure that o ne actually has the
value fo r e quals as well, o therwise yo u'll miss the "edge case"peo ple who are exactly 15! Let's go ahead
and fix that:

CODE TO TYPE:
import java.applet.Applet;
import java.awt.*;
public class Driving extends Applet {
int age = 15;
public void paint(Graphics g) {
if (age > 15)
{
g.drawString ("Congratulations", 50, 50);
g.drawString ("You may drive", 50, 70);
}
if (age <= 15)
{
g.drawString ("Wait a few years", 50, 50);
g.drawString ("You may not drive yet", 50, 70);
}
g.drawString("Age is " + age, 50, 90);
}
}
NOW the two examples are equivalent. Why wo uld we use e lse s rather than two if s? One reaso n is speed.
Java do es no t have to go back to the age variable in memo ry to see what its value is a seco nd time if there is
an e lse . Or perhaps yo u, as a pro grammer, think that two if s will be mo re efficient o r mo re clear than o ne.
This co uld be true, but yo u still need to be careful.
So no w that we've talked abo ut the last two parts o f the if statement, maybe we sho uld discuss the first part a
little mo re!

Comparison Operators and Logic


The first co mpo nent o f if statements is the co nditio nal. Is so mething t rue o r f alse ? Just like we have the arithmetic
o perato rs (-, *, /, and %) to manipulate numbers and change variable values, we also have o perato rs to determine ho w
variable values are related and to co m pare them.

Comparison Operators
We've already used so me co mpariso n o perato rs in the examples abo ve, such as <, >, and ==. Here's a mo re
co mplete list:
>

greater than

<

less than

== equal to (true when two objects are the same, o r two primitive data types have the same value)
!=

no t equal to

<= less than o r equal to


>= greater than o r equal to
(Mo re o perato rs exist that deal with co mpariso ns o f single bits at a time, but that's beyo nd the sco pe o f this
class.)
Let's lo o k mo re clo sely at the ==. Remember that in co mputer languages, o ne equals sign tells the co mpiler
to put the value o n the right into the address o n the left, as we did with int age = 15 . Fo r two equals signs,
when the variables o n bo th sides are inst ance s o f so me Class, yo u're asking if the variable o n the left side
points to the same object as the variable o n the right side. If the variable has a value that is a primitive data
type, then the == is co mparing to see if the value o n the left is the same as the value o n the right.
We o ften have mo re than o ne thing to co mpare when we make decisio ns. Given this, we need to use
additio nal logic. We'll co ver co mputer lo gic in depth in the seco nd co urse o f this series.
See yo u in the next lesso n...
Copyright 1998-2014 O'Reilly Media, Inc.

Copyright 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Objects and Classes


When yo u co mplete this lesso n, yo u will be able to :

Lesson Objectives
define a class's Objects and present them lo gically.
declare a class and assign it so me attributes.
declare variables.

Objects
In the last lesso n, we created and ran Applets. To reiterate, a running Applet is an example o f an Obje ct . In o bjecto riented pro gramming, everything is do ne thro ugh Objects. This lesso n will fo cus o n tho se Objects that peo ple like us
in the pro gramming have defined and created them fo r specific purpo ses.

What is an Object?
An Object is a co mbinatio n o f dat a (pro pe rt ie s, variable s, f ie lds) and act io ns (f unct io ns, m e t ho ds).
An Object has a state o f being o r at t ribut e such as co lo rOf Eye s, pro f e ssio n, le ngt h, o r lo cat io n, and
behavio rs o r m e t ho ds it can perfo rm to change its state o f being, like ge t Ne wJ o b, payAt t e nt io n, o r walk.
Yo u may have no ticed that we use so me funky wo rds. Well, they're created that way because co mputer
co mpilers/interpreters do no t like spaces in variable and metho d names. When creating names fo r their
o bjects, pro grammers cram the wo rds to gether witho ut spaces, begin each name with a lo wer case letter, and
capitalize the first letter o f each subsequent wo rd in the name, all acco rding to co nventio n.
So metimes pro grammers will use mo re technical terms to describe state and behavio r and refer to an Object
as a co mbinatio n o f data (pro perties, variables, fields) and actio ns (functio ns, metho ds).
But it's useful to think o f Objects as real Objects when designing a pro gram. That the characteristics and
capabilities o f Objects belo ng to the very o bjects that sho uld po ssess them. In pro gramming terms, the
metho ds and attributes that the Object is capable o f are co ntained within the Object definitio n.
Inexperienced pro grammers tend to put info rmatio n in all kinds o f weird places. Yo u want yo ur Objects to be
o rganized clearly and co ntain the right info rmatio n, since o ther pro grammers might use yo ur Objects to o .
Like we said, sharing is the greatest benefit o f Object Oriented pro gramming!
Fo r example, if I were to ask yo u what co lo r my cat Missy's eyes were, in what Object might yo u lo o k to find
the answer? (Pretend that we've created all o f these as Java Objects):
Me (since Missy is my cat)?
Humans (since she is mine and I am a human)?
Eyes?
Cats?
Missy?

All o f these things are Objects, but which o ne sho uld have a value fo r the co lo r o f her eyes? Ho pefully yo u
reco gnized that info rmatio n abo ut the co lo r o f the cat Missy's eyes belo ngs in the Object Missy. The Object
Missy sho uld have an at t ribut e o f e ye Co lo r and the value o f that attribute wo uld be gre e n.

In o bject-o riented pro gramming, the first thing we do is define Classes o f Objects. We define an instance o f
an Object by letting it have the characteristics and behavio rs that belo ng to that Object.
Objects can also inherit fro m o ther Objects. Fo r instance, Missy is a cat. She shares attributes in co mmo n
with o ther cats like fur and claws, and actio ns like purring and hacking up furballs. What do es Missy inherit
fro m Cats? Certainly she inherits legs, a tail, whiskers, and such. But what makes Missy uniquely Missy? That
wo uld be her specific fur co lo r, eye co lo r, so me behavio rs, and the like.
If we were to pro gram Missy in Java we'd make a Missy class that creates instances o f Missy.
OBSERVE:
import java.cats.*
public class Missy extends cats {
Color colorOfEyes = color.green;
Color colorOfFur = color.gray;
Boolean hungry = True;
public Sound meow() {
if (hungry) {
Sound talk = "cry";
}
else
{
Sound talk = "purrrr";
}
return talk;
}
}
What Java syntax did we use to specify inheritance? In fact, yo u may remember do ing so mething similar
befo re when yo u extended Applet. In o ur Duke Applet fro m the previo us lesso n:
OBSERVE:
public class Duke extends Applet
Since o ur Duke inherited fro m Apple t , any Objects made fro m these class templates inherited all o f the
attributes and actio ns o f the Apple t class to o . Kno wing the similarities and differences amo ng Classes will
help yo u decide the best classes fo r yo ur Objects to inherit fro m, and also help yo u define Classes.
Co nsider o ur friend Duke again. In the next sectio n, we will enhance o ur earlier co de and make a template fo r
Duke o bjects. (He is simply never go ing away!)

Classes
The declaratio n (o r definitio n) o f the structure o f o bjects o f a certain kind is called a Class. A class is a
template o r a blueprint fo r creating instances o f o bjects.
The Duke Class we made earlier is a template that creates instances which are specifically Duke Objects.
Think o f Class as a machine that creates Objects. Yo u do n't actually get an Object fro m a Class until the Java
co de is executed, but as yo u'll see in the upco ming example, yo u can get different instances o f Objects fro m a
single Class. We can do that by setting attributes and calling metho ds that are made available to us by the
Class.

To define a Class, we give it attributes that define that particular type o f Object and thus pro vide its state (the
variables) and also the behavio rs that the Object is capable o f perfo rming (the methods).

Note

The metho ds and fields o f a Class are so metimes called the Class Me m be rs

Let's take yet ano ther lo o k at Duke. So far in o ur pro gram we haven't given Duke any attributes. We've simply
printed pictures o f Duke do ing different things. Let's change that. Let's start giving Duke so me attributes. What
attributes sho uld we give Duke?
What makes Duke a Duke? Well, Duke is an Applet because he extends Applet. But Duke isn't just an Applet
he has so me o f his o wn attributes as well. Yo u can see he always has a po inty head, two arms, a ro und
no se, and a to o th-shaped bo dy. Hmm, do es a Duke have to be a bo y? Co uld there be a Duke with a blue
no se? It's really all up to yo u.
Our next task in Java will be to add a new attribute to o ur Duke. Every Duke has a no se. Let's suppo se so me
Dukes have different co lo r no ses. Let's make a Duke class that has an attribute o f no se Co lo r with two
po ssible no se co lo rs: red and blue. Befo re we pick Duke's no se (as it were), let's go o ver so me effective
techniques to use when designing Objects:
When cho o sing o bje ct s/classe s, lo o k fo r no uns in the pro gram. Our class is called Duke .
When cho o sing m e t ho ds, lo o k fo r ve rbs in the pro gram. Ours are wave (), writ e (), and t hink().
When cho o sing a pro gram's f ie lds and at t ribut e value s lo o k fo r persistent charact e rist ics o f
the o bjects. No w we're abo ut to add an attribute called no se Co lo r.
Let's make a new pro ject fo r Lesso n 6 , named java1_Le sso n0 6 .
Let's build o n the Duke class we created already. Co py the Duke.java file fro m java1_Lesso n0 4 to
java1_Lesso n0 6 :
1. Select java1_Le sso n0 4 in the Package Explo rer windo w.
2. Click the + sign to o pen the Pro ject; if the de f ault package is clo sed, click o n its + as well.
3. Right-click Duke .java and select Co py.
4. Right-click the java1_Le sso n0 6 /src fo lder and cho o se Past e . Yo u sho uld see a de f ault
package with Duke .java in it.
No w, let's edit o ur Duke.java and check o ut ho w Objects wo rk:
Open the java1_Le sso n0 6 /src subfo lder, and its de f ault package . Then, do uble-click the Duke .java
pro gram to o pen it in yo ur Edito r Windo w.
Remember, click the encircled + sign if yo u see this in the impo rts:

Yo u sho uld see:

Note

The fo rward slashes // in Java indicate comments. Yo u can use them to pro vide helpful
info rmatio n within yo ur co de. When Java runs the co de, it igno res everything fro m the // to the
end o f the line.

This next example will be a little different fro m stuff we've do ne befo re. We wo n't lo o k at the actio ns o f Duke
o ne at a time, but instead we'll o bserve them randomly.
Edit Duke.java as fo llo ws (adding co de that lo o ks like this and remo ving co de like this):

CODE TO TYPE:
import java.awt.*;
import java.applet.Applet;
public class Duke extends Applet {
int test = 0;
Image action;
Color noseColor = Color.red;
public void paint(Graphics g) {
// Next line randomly picks just to show that different noses are possib
le.
int rint = (int)(Math.random() * 2); // Gives either a 0 or a 1.
if (rint == 0) {
noseColor = Color.red;
} else {
noseColor = Color.blue;
}
// Randomly let this duke do something - one of 3 choices.
switch ((int)(Math.random() * 3))
// Gives a number between 0 and 2 in
clusive.
{
case 0: action= this.write(g); break;
case 1: action= this.think(g); break;
case 2: action= this.wave(g); break;
}
resize(300,300); // Resize the applet window.
g.drawImage(action, 10, 10, Color.white, this);
test = test + 1;
//
Show that Restart repaints to make a new action.
if

(noseColor != Color.red) {
g.drawString("My nose feels funny", 10, 145);

}
}
public Image write(Graphics graph){
graph.drawString("I am a writing Duke", 10,130);
if (noseColor == Color.red){
action = getImage(getDocumentBase(),"../../images/duke/penduke.gif")
;
} else {
action = getImage(getDocumentBase(),"../../images/duke/penduke2.gif"
);
}
return action;
}
public Image think(Graphics graph){
graph.drawString("I am a thinking Duke", 10,130);
if (noseColor == Color.red){
action = getImage(getDocumentBase(),"../../images/duke/thinking.gif"
);
} else {
action = getImage(getDocumentBase(),"../../images/duke/thinking2.gif
");
}
return action;
}
public Image wave(Graphics graph){
graph.drawString("I am a waving Duke", 10,130);
if (noseColor == Color.red){
action = getImage(getDocumentBase(),"../../images/duke/dukeWave.gif"

);
} else {
action = getImage(getDocumentBase(),"../../images/duke/dukeWave2.gif
");
}
return action;
}
}
Make sure yo u've typed it all co rrectly. Yo u sho uldn't see any erro rs; just the o ne warning abo ut the
serializable class at the beginning o f the class definitio n.
Save and run it.

Note

No tice the applet windo w is larger. We set that with the statement re size (30 0 ,30 0 ). The first
argument sets the windo w's width, the seco nd sets the height.

Resto re do wn the lesso n windo w. Keep the first Duke


Applet running and mo ve it to the right.
Run it again to make ano ther o ne and mo ve it to the right.
Run it again and mo ve it to the right.
And

Run it yet again.

No w the Applets are all o nscreen:

No tice that so metimes we get a Duke with a re d no se and so metimes we get a Duke with a blue no se .
What have we do ne? This time we didn't Restart an existing Applet, but Ran a new o ne. Each time yo u run an
Applet, yo u're creating a new Applet and hence a new Duke Object. No tice in the co de that Duke e xt e nds the
Class Applet, so Duke inherits fro m Applet and thus we say Duke is an Applet.

So , every time we run the Applet, we get a new Applet Object and we are getting a new and different Duke
(No te that because o ur algo rithm is rando m, we might also get the same Duke twice). Each o f these windo ws
sho ws a new instance o f the Applet and hence a new instance o f Dukewith all o f the inherited characteristics
fro m Applet and all o f the characteristics specified in the Duke template.

Note

Each time we use a Class to make o ne o f the things that are described by o ur Class template,
we are creating an instance o f the class (called an Object).

We call this instantiation.


Specifically, we have a class template named Duke which e xt e nds Apple t . The co de written describes the
class's attributes and metho ds. Each time we run the co de, we generate a brand new Duke po ssessing all o f
tho se attributes and metho ds.
Since everything in Java is no t an Applet, we do n't always have Applets to make different instances fo r us. In
o rder to make instances o f Classes, Classes usually pro vide a special metho d (a Co nst ruct o r) that is
called o r invoked when so meo ne wants to "co nstruct" an instance o f that class. (Mo re o n this to pic later.)
Let's lo o k at the co de in a bit mo re detail to get a tho ro ugh understanding o f each part:

OBSERVE:
import java.awt.*;
import java.applet.Applet;
public class Duke extends Applet {
Image action;
Color noseColor = Color.red;
public void paint(Graphics graph) {
// Next line randomly picks just to show that different noses are possible.
int rint = (int)(Math.random() * 2); // Gives either a 0 or a 1.
if (rint == 0) {
noseColor = Color.red;
} else {
noseColor = Color.blue;
}
// Randomly let this duke do something - one of 3 choices.
switch ((int)(Math.random() * 3))
// Gives a number between 0 and 2 in
clusive.
{
case 0: action= this.write(graph); break;
case 1: action= this.think(graph); break;
case 2: action= this.wave(graph); break;
}
graph.drawImage(action, 10, 10, Color.white, this);
if (noseColor != Color.red){
graph.drawString("My nose feels funny", 10,145);
}
}
public Image wave(Graphics g) {
g.drawString("I am a waving Duke", 10,130);
if (noseColor == Color.red){
action = getImage(getDocumentBase(),"../../images/duke/dukeWave.gif"
);
} else {
action = getImage(getDocumentBase(),"../../images/duke/dukeWave2.gif
");
}
return action;
}
public Image write(Graphics g){
g.drawString("I am a writing Duke", 10,130);>
if (noseColor == Color.red){
action = getImage(getDocumentBase(),"../../images/duke/penduke.gif")
;
} else {
action = getImage(getDocumentBase(),"../../images/duke/penduke2.gif"
);
}
return action;
}
public Image think(Graphics g){
g.drawString("I am a thinking Duke", 10,130);
if (noseColor == Color.red){
action = getImage(getDocumentBase(),"../../images/duke/thinking.gif"
);
} else {
action = getImage(getDocumentBase(),"../../images/duke/thinking2.gif
");
}
return action;
}

}
Co lo r no se Co lo r = Co lo r.re d; initially sets the no seCo lo r attribute to red. The next co uple o f references to
no seCo lo r are within an if statement that checks a rando m integer we call rint , which can be 0 o r 1. If it's zero .
the no seCo lo r stays red; if it's 1 (that is, "else no t 0 "), we set the no seCo lo r attribute to blue. The next
reference to no seCo lo r appears where we check to see if t he no se Co lo r isn't re d; if it isn't, we print "My
no se feels funny". The remaining references to no seCo lo r all check to see if the attribute is set to red o r no t. If
it is, then we put up the picture o f Duke with a red no se, o therwise we put up the alternate picture o f Duke.
We also changed o ur switch statement to wo rk rando m ly, rather than in sequence.
No tice in the example abo ve, the variable rint is declared inside o f the paint (Graphics graph) metho d. This
is called a lo cal variable . Its sco pe is so lely within the blo ck o f co de (that is to say, within the curly brace s {
} ) in which it was declared. This means that if we were to try to access this variable fro m anywhere o utside o f
the paint () metho d, we wo uld get a co mpile erro r, because the rint variable o nly exists within the paint ()
metho d.
Lo cal variables can be defined within any blo ck o f co de defined by curly braces o r any co nditio nal o r lo o p that
do es no t need curly braces. Ho wever, defining them in a co nditio nal o r lo o p that do es no t need curly braces
wo uld be useless, since they co uld o nly be accessed in that single line o f co de.
Example
if(x > 10){
int y = 30;
}
System.out.println(y);
In this sho rt example, the variable y o nly exists within the if statement, so the System.o ut.println(y) statement
wo uld cause a co mpile erro r.

Java Data T ypes


The Java pro gramming language is stro ngly typed, which means that all variables must first be declared
befo re they can be used. This invo lves stating the variable's t ype and name, as yo u've already seen in these
lesso ns. Like:
Im age Actio n;
and:
Co lo r no seCo lo r = Co lo r.red;
and:
int rint = (int)(Math.rando m() * 2);
So me o f the types are primitive data types and so me o f them are Object Data Types. Yo u can tell the
difference because Object data types are Capitalized and primitive data types start with a lo wercase letter (like
int).
Declaring a variable tells yo ur pro gram that a field exists (with whatever name yo u cho o se, like no se Co lo r
o r Act io n), it ho lds data, and has so me initial value. If yo u do n't give an initial value, mo st types have a
default initial value. A variable's data type determines the values it may co ntain, plus the o peratio ns that may
be perfo rmed o n it. In additio n to int, the Java pro gramming language suppo rts seven o ther primitive data
types. A primitive type is predefined and is named by a reserved keywo rd. The eight primitive data types
suppo rted by the Java pro gramming language are (yo u do n't need to understand all o f this but read o ver it.
We'll be co vering these in mo re detail in the seco nd co urse o f this series. Pay particular attentio n to int,
do uble, and bo o lean):

byte

sho rt

An 8 -bit signed two 's-co mplement integer. It has a minimum value o f -128 and a maximum
value o f 127 (inclusive). The byte data type can be useful fo r saving memo ry in large arrays,
where the memo ry savings actually matters. They can also be used in place o f int where their
limits help to clarify yo ur co de; the fact that a variable's range is limited can serve as a fo rm o f
do cumentatio n.
A 16 -bit signed two 's-co mplement integer. It has a minimum value o f -32,76 8 and a maximum
value o f 32,76 7 (inclusive). As with byte, the same guidelines apply: yo u can use a sho rt to save

memo ry in large arrays, in situatio ns where the memo ry savings actually matters.

int

A 32-bit signed two 's-co mplement integer. It has a minimum value o f -2,147,48 3,6 48 and a
maximum value o f 2,147,48 3,6 47 (inclusive). Fo r integral values, this data type is generally the
default cho ice unless there is a reaso n (like the abo ve) to cho o se so mething else. This data
type will mo st likely be large eno ugh fo r the numbers yo ur pro gram will use, but if yo u need a
wider range o f values, use lo ng instead.

lo ng

A 6 4-bit signed two 's-co mplement integer. It has a minimum value o f 9 ,223,372,0 36 ,8 54,775,8 0 8 and a maximum value o f 9 ,223,372,0 36 ,8 54,775,8 0 7 (inclusive).
Use this data type when yo u need a range o f values wider than tho se pro vided by int.

flo at

A single-precisio n 32-bit IEEE 754 flo ating po int. Its range o f values is beyo nd the sco pe o f this
discussio n, but is specified in sectio n 4.2.3 o f the Java Language Specificatio n. As with the
reco mmendatio ns fo r byte and sho rt, use a flo at (instead o f do uble) if yo u need to save
memo ry in large arrays o f flo ating po int numbers. This data type sho uld never be used fo r
precise values, such as currencyfo r that, use the java.math.BigDecimal class instead.
Numbers and Strings co ver BigDecimal and o ther useful classes pro vided by the Java platfo rm.

do uble

A do uble-precisio n 6 4-bit IEEE 754 flo ating po int. Its range o f values is beyo nd the sco pe o f
this discussio n, but is specified in sectio n 4.2.3 o f the Java Language Specificatio n. Fo r decimal
values, this data type is generally the default cho ice. As mentio ned abo ve, this data type sho uld
never be used fo r precise values, such as currency.

bo o lean

Has o nly two po ssible values: true and false. Use this data type fo r simple flags that track
true/false co nditio ns. This data type represents o ne bit o f info rmatio n.

char

A single 16 -bit Unico de character. It has a minimum value o f '\u0 0 0 0 ' (o r 0 ) and a maximum
value o f '\uffff' (o r 6 5,535 inclusive).

In this co urse we've been using int and bo o lean a lo t.


The o ther kinds o f types we're using are Object types like Co lo r and Image, when yo u declare a variable to be
o f tho se types it really means that yo u're either go ing to create an instance o f that type with the variable name,
o r yo u're go ing to set the variable to an o bject o f that type.
When we say Co lo r no se Co lo r = Co lo r.RED, we are setting no seCo lo r to be a Co lo r o bject. We co uld
also say Co lo r no se Co lo r = ne w Co lo r(25 5 ,0 ,0 ); ((255,0 ,0 ) is the RGB value o f red). In fact Co lo r.RED is
defined in the co lo r class exactly the same way using new Color(255,0,0). We'll co ver this mo re later. Fo r no w,
I just want yo u to kno w what yo u are typing when yo u type in the variable declaratio ns.
Copyright 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Classes and Instances


When yo u co mplete this lesso n, yo u will be able to :

Lesson Objectives
use the co nstructo r metho d.
create multiple instances o f an applet to execute different characteristics and actio ns.

Object Design
Okay kids, it's time to get serio us abo ut making things mo re Object Oriented. So far we've played aro und with an
Applet that executes actio ns and has characteristics, but everything we've do ne has been within a single Class. In this
lesso n we'll put Duke into a class o f his o wn and let the Applet do what it's go o d at--grabbing stuff and putting it o n the
screen. And we'll let the Duke Class do what it sho uld be go o d at, which is creating instances o f Dukes that execute
different actio ns and characteristics.

Who gets what?


Since yo u kno w ho w to start a new pro ject no w, let's create o ne. Call it java1_Le sso n0 7 and then give Duke
a nice clean Class o f his o wn that we'll call Duke s (plural). This time tho ugh, the class wo n't be extending
Applet. Instead we'll create a different Class fo r that. It will use the Class we're making no w. Yo u'll see ho w
this all wo rks in a minute.
1. Start a new pro ject called java1_Le sso n0 7 .
2. Make a new class named Duke s (plural!).

To
do

3. The dialo g sho uld have So urce f o lde r: java1_Lesso n0 7 (o r


java1_Lesso n0 7/src).
4. Give it Nam e : Duke s.
5. This time DON'T change t he supe rclass: java.lang.Obje ct .
6 . Click Finish.

.
Duke s will no t be an Applet, which is why its Superclass sho uld remain java.lang.Obje ct .
Type in the blue co de belo w:

CODE TO TYPE
public class Dukes {
private
private
s are friendly
private
private

Color noseColor = Color.red; // default Dukes have red noses


String action = "../../images/duke/dukeWave.gif"; //default Duke
String whatDoing = "Give me something to do";
String message= "";

public Dukes()
{
int rint = (int)(Math.random() * 3);

// randomly generates a 0, 1,

or 2
if (rint == 0)
{
noseColor = Color.blue;
// more often red by default
action = "../../images/duke/dukeWave2.gif";
message = "What's up with the blue nose!";
}
}
public String getAction()
{
return whatDoing;
}
public String getActionImage()
{
return action;
}
public Color getNoseColor()
{
return noseColor;
}
public String getMessage()
{
return message;
}
public String write()
{
whatDoing = "I am a writing Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/penduke.gif";
message = "";
}
else
{
action = "../../images/duke/penduke2.gif";
message = "My nose feels funny";
}
return action;
}
public String think()
{
whatDoing = "I am a thinking Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/thinking.gif";
message = "";
}
else

{
action = "../../images/duke/thinking2.gif";
message = "My nose feels funny";
}
return action;
}
public String wave()
{
whatDoing = "I am a waving Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/dukeWave.gif";
message = "";
}
else
{
action = "../../images/duke/dukeWave2.gif";
message = "My nose feels funny";
}
return action;
}
}

This is just a Java class and wo n't actually run, but yo u sho uld SAVE it anyway. Only applicatio ns and
Applets will run. Go ahead and try to run it, just so yo u can o bserve the erro r.
No w let's break the co de do wn bit by bit to see what this class is all abo ut.
The first part o f the definitio n o f the Dukes Class is lo cated o n the first line. Immediately after that we have
so me At t ribut e s (variables) defined. Igno re the italicized text fo r no w; we'll discuss that sho rtly. Fo r no w,
pay attentio n to the co lo re d t e xt :

OBSERVE: The co lo red text belo w


public class Dukes {
private Color noseColor = Color.red; // default Duke's have red nose
s
private String action = "../../images/duke/dukeWave2.gif"; //default
dukes are friendly
private String whatDoing = "Give me something to do";
private String message = "";
public Dukes()
{
int rint = (int)(Math.random() * 3);

// randomly generates a 0,

1, or 2
if (rint == 0)
{
noseColor = Color.blue;
// more often red by default
action = "../../images/duke/dukeWave2.gif";
message = "What's up with the blue nose!";
}
}
public String getAction()
{
return whatDoing;
}
public String getActionImage()
{
return action;
}
public Color getNoseColor()
{
return noseColor;
}
public String getMessage()
{
return message;
}
public String write()
{
whatDoing = "I am a writing Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/penduke.gif";
message = "";
}
else
{
action = "../../images/duke/penduke2.gif";
message = "My nose feels funny";
}
return action;
}
public String think()
{
whatDoing = "I am a thinking Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/thinking.gif";
message = "";
}
else

{
action = "../../images/duke/thinking2.gif";
message = "My nose feels funny";
}
return action;
}
public String wave()
{
whatDoing = "I am a waving Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/dukeWave.gif";
message = "";
}
else
{
action = "../../images/duke/dukeWave2.gif";
message = "My nose feels funny";
}
return action;
}
}
If we had inherited fro m so mething o ther than the default o f java.lang.Obje ct , we'd see the e xt e nds
keywo rd identifying the supe rclass o n the first line, just like befo re when we extended the Applet class. Yo u
do n't need to extend Object because Java assumes every Class extends it. As so o n as the Class is named
in the definitio n, we begin defining its attributes (no se Co lo r, what Do ing, act io n, and m e ssage ).
No tice that no t o nly did we define the t ype these attributes take, but we made them privat e . So what's this
public and privat e stuff all abo ut, yo u ask? Well, when we make Classes, we usually make them fo r o ther
Classes to access and use. That's why we set permissio ns o n the members o f a Class that o ther Classes
can access. Pe rm issio ns can be public, privat e , o r pro t e ct e d. (We'll discuss o ther impo rtant aspects o f
these mo difiers in a later lesso n.) Fo r no w we'll just study two permissio ns: public and privat e .
The Instance Variables (attributes) listed abo ve are all privat e and the class definitio n and acce ss m e t ho ds
are all public. The re se rve d wo rds o f public and privat e are mo difiers present in o rder to indicate access
capabilities fo r Fields and Metho ds. Since Classes are made fo r o ther Classes to use, we use public and
privat e to determine the capabilities they can access. Public Metho ds usually o nly serve to get o r change
the values o f privat e members, and are referred to as ge t t e rs (gets) and se t t e rs (puts/changes). They are
so metimes referred to as accesso rs and mutato rs as well. The idea behind all o f this is fo r o ur co de to be
e ncapsulat e d and o ur dat a/inf o rm at io n t o be hidde n. That way we o nly allo w the values o f the
variables to be changed o r accessed t hro ugh t he se acce sso r and m ut at o r m e t ho ds. Thus the
variables themselves are private, but access to them may be public (o f co urse, these members are
accessible inside o f their o wn classes). Limiting access this way helps to prevent data co rruptio n.
Fo r example, in this Class we've go t so me acce sso rs called ge t Act io n(), ge t Act io nIm age (),
ge t No se Co lo r(), and ge t Me ssage (). These metho ds were made specifically to allo w pro grammers to get
the values o f the variables what Do ing, act io n, no se Co lo r, and m e ssage , respectively, witho ut accessing
them directly. So no w we have two sets o f metho ds, o ne made up o f accesso rs { getActio n(),
getActio nImage(), getNo seCo lo r(), and getMessage() } and the o ther made up o f actio ns that Dukes can
perform { write(), think(), and wave() }.
In the Dukes class, we allo w each o f the Dukes to have characteristics. The Class defines attributes o f
no seCo lo r (o f type Co lo r), an act io n this particular Duke can take (o f type St ring), and the m e ssage this
particular Duke can give us (o f type St ring).

Accesso r Metho ds in Dukes


public String getAction()
{
return whatDoing;
}
public String getActionImage()
{
return action;
}
public Color getNoseColor()
{
return noseColor;
}
public String getMessage()
{
return message;
}

The remaining metho ds are the no w familar act io ns o f a Dukes o bject, that is, they are the things that Dukes
can do : write(), think(), wave().

Actio n Metho ds in Dukes


public String write()
{
whatDoing = "I am a writing Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/penduke.gif";
message = "";
}
else
{
action = "../../images/duke/penduke2.gif";
message = "My nose feels funny";
}
return action;
}
public String think()
{
whatDoing = "I am a thinking Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/thinking.gif";
message = "";
}
else
{
action = "../../images/duke/thinking2.gif";
message = "My nose feels funny";
}
return action;
}
public String wave()
{
whatDoing = "I am a waving Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/dukeWave.gif";
message = "";
}
else
{
action = "../../images/duke/dukeWave2.gif";
message = "My nose feels funny";
}
return action;
}
}
Finally, there's o ne special metho d type called the Co nst ruct o r:
Dukes Co nstructo r Dukes()
public Dukes()
{
int rint = (int)(Math.random() * 3); // randomly generates a 0,
1, or 2
if (rint == 0)
{
noseColor = Color.blue;
// more often red by default
action = "../../images/duke/dukeWave2.gif";
message = "What's up with the blue nose!";
}
}

The italicized code fro m abo ve defines this Class's Constructor. A co nstructo r is the metho d that's called to
create an instance o f a Class. If yo u do n't pro vide a co nstructo r definitio n, a default co nstructo r witho ut
parameters is created auto matically (we'll get to that later). Co nst ruct o rs always have t he sam e nam e as
t hat o f t he Class. That's why there is a metho d called Duke s() in this co de. When we write ano ther Class
that instantiates this Dukes Class, we'll have to call this metho d which then constructs Dukes instances fo r us
(we'll give this a try later in the lesso n).
In this Dukes Class, the Co nstructo r determines the no se Co lo r o f this Duke's no se, the act io n this
Duke takes, and the initial m e ssage to send fro m this Duke. The co de in this particular co nstructo r picks a
rando m number fro m amo ng 0 , 1, and 2. Only if it selects 0 do es it give Duke a blue no se, o therwise his no se
stays red.
It's impo rtant to be able to discern the vario us parts o f the definitio ns o f classes, altho ugh in essence, a class
o nly has m e t ho ds and variable s. In the API they use the term Fie lds instead o f "Variables", so yo u might
see a Fie ld Sum m ary. Do n't wo rry, it's just a variable.
In additio n, a lo t o f co de o rganizatio n is do ne using blo cks. Java uses blo cks o f co de to specify definitio ns
fo r classes, metho ds, and o ther gro upings o f co de. Brackets {} are used to begin and end blo cks. Blo cks are
also called co m po und st at e m e nt s because they can be used to define o r gro up to gether mo re than o ne
statement.

T o do

1. Let's match so me blo cks o f co de.

Eclipse can help us identify blo cks o f co de. Click directly af t e r an o pening bracket { anywhere in the
Dukes.java class. No tice that there's a little rectangle aro und its clo sing bracket } . Eclipse will identify the
matching o pening bracket when yo u click after the clo sing bracket.
Re m e m be r, the { } blo cks help us identify the metho ds o f a class. The fields/variables will no t have blo cks
o f their o wn and sho uld always be either at the very beginning o f the class definitio n blo ck, after the o pening {,
o r at the very end o f the class definitio n blo ck, befo re the clo sing } . This will make yo ur pro gram mo re
readable.

Initialization and Constructors


De f ault s
Classes are the templates fo r Objects. The Class definitio n sets up the way Objects will lo o k when they're
instantiated. Defaults can be used to give instances initial standard values. In o ur definitio n o f Dukes, Dukes
will "no rmally" have red no ses, and then tho se Dukes willl have default actio ns.
Default values
private
private
re friendly
private
private

Color noseColor = Color.red; // default Duke's have red noses


String action = "../../images/duke/dukeWave2.gif"; //default dukes a
String whatDoing = "Give me something to do";
String message = ""; //initial message is blank

In additio n to the abo ve default values fo r the attributes, a Class's co nstructo r is used to make a specific
instance o f the Class and is usually used to reset so me o f the Attributes fo r that instance. In o ur case, the
Dukes co nstructo r is used to decide the co lo r o f this particular Duke's no se. No rmally Dukes will have a red
no se Co lo r by default, but o ur Co nstructo r has co de in it that can change that upo n instantiatio n depending
o n a rando m variable (rint ). Similarly, we set the Dukes default act io n to wave. Ho wever, if yo u lo o k in the
Dukes co nstructo r, we are generating rando m numbers o f 0 , 1, and 2 that will ultimately determine which
characteristics an instantiated Duke will have. If the rando m number happens to be 0 , we are giving that
instance o f Dukes a blue no se. Since the blue-no sed, waving Duke must have a blue no se, we are also
changing the default waving red-no sed Duke (dukeWave.gif) to a waving blue-no sed Duke (image o f
dukeWave.gif).
Co nstructo rs have specific characteristics that differ fro m o ther metho ds. Remember, they always have the
same name (case-sensitive) as the class, and the pro grammer never specifies that they "return" anything,
since the co nstructo r always returns exactly o ne thing--an instance o f this type o f class.

We're go ing to get Duke's fingers mo ving in the next sectio ns by building so me Applets that use the Dukes class we
created in this sectio n. This might be a go o d time to take a break o r maybe even take a nap.
.

Making an Applet for Dukes


If yo u haven't go t it o pened already, o pen up the Duke s.java file we wo rked o n in the previo us sectio n. Yo u
may no tice that Eclipse is giving us so me erro rs:

Do uble-click o n tho se erro rs fo r suggestio ns fo r fixing them. Always try the first suggested fix first because it
might also fix so me o f the erro rs farther o n do wn the chain. Go ahead and try the first suggestio n. It wo rked,
didn't it? Did all o f yo ur erro rs go away? Co o l, huh? At the to p o f yo ur Dukes.java file yo u sho uld see this:
At the to p o f yo ur Dukes.java file:
import java.awt.Color;

That's because we're using the co lo rs fro m the Co lo r o bject.


Since the class Dukes is no t an Applet (remember--he is a java.lang.Object), we need to make an Applet that
will use instances o f Dukes and display them.
Start a ne w class called Duke sApple t and m ake sure it extends Applet this time. Its superclass sho uld be
java.apple t .Apple t .

CODE TO TYPE: DukesApplet


import java.awt.*;
import java.applet.Applet;
public class DukesApplet extends Applet{
Dukes myDuke;
public void init()
{
myDuke = new Dukes();
}
public void paint(Graphics g)
{
String action="";
switch ((int)(Math.random() * 3))
{
case 0: action= myDuke.write(); break;
case 1: action= myDuke.think(); break;
case 2: action= myDuke.wave(); break;
}
Image myAction = getImage(getDocumentBase(), action);
g.drawString(myDuke.getAction(), 10,130);
g.drawString(myDuke.getMessage(), 10,145);
g.drawImage(myAction, 10, 10, Color.white, this);
}
}
Run it.
The o utput is the same as befo re, but the co de is much different this time. Let's lo o k at what this co de is do ing
differently.
No tice that this Class e xt e nds Apple t . As we mentio ned, the Java peo ple already wro te the Class Apple t
and the Class Graphics used by Applets. No w let's take a lo o k at this Applet and see ho w we've
inco rpo rated the Dukes class we made earlier.

DukesApplet
import java.awt.*;
import java.applet.Applet;
public class DukesApplet extends Applet{
Dukes myDuke;
public void init()
{
myDuke = new Dukes();
}
public void paint(Graphics g)
{
String action="";
switch ((int)(Math.random() * 3))
{
case 0: action= myDuke.write(); break;
case 1: action= myDuke.think(); break;
case 2: action= myDuke.wave(); break;
}
Image myAction = getImage(getDocumentBase(), action);
g.drawString(myDuke.getAction(), 10,130);
g.drawString(myDuke.getMessage(), 10,145);
g.drawImage(myAction, 10, 10, Color.white, this);
}
}
Here we instantiated and used an o bject fro m a Class we created. In do ing so , we created an Inst ance
Variable that has the type o f the o bject name. In this case we wro te: Duke s m yDuke , thus the instance
variable myDuke is o f type Dukes. No w we need to give m yDuke a value. That's where the Co nst ruct o r
Duke s() fro m the Dukes class co mes in. When we write m yDuke = ne w Duke s(), Java uses the co nstructo r
to create an instance o f Dukes, which in turn sets any attributes we put into the Dukes() co nstructo r. No w that
we have an instance o f Dukes o n o ur hands (myDukes), we can use the metho ds o f Dukes ho wever we wish.
To access metho ds o f Dukes, we simply use the syntax m yDuke s.m e t ho dNam e ().
No w instead o f having to write the think(), wave(), and write() metho ds, we can simply reuse the metho ds that
are in the Dukes() Class. We also used the getActio n() and getMessage() metho ds to access the message
and actio n that were set in the Dukes class. Also , no tice that the act io n variable in this Class is no t the same
as the actio n variable in the Dukes Class.
This co de is mo re mo dular and encapsulated than o ur first Applet. This new Applet specifies things to
perfo rm using o nly Applet's native metho ds, such as init () and paint (Graphics g). It's a better design.
No tice the init () metho d. It's in this metho d that we cre at e o r inst ant iat e o ur inst ance o f the Dukes class.
Classes that are no t Applets are instantiated with the ne w co mmand.
Like all variables, yo u can declare and instantiate (give value) in o ne line:
Dukes myDuke = new Dukes();
In general, when yo u create a new o bject by invo king a co nstructo r, yo u can do it in o ne o r two lines.
OBSERVE: Declare and Instantiate
Dukes myDuke;
myDuke = new Dukes();
or
Dukes myDuke = new Dukes();
In the first case, Duke s m yDuke is o nly de claring that myDuke is go ing to be o f t ype Dukes. Remember
when Eclipse said, "canno t reso lve the type" o f so mething? Everything in Java must be de clare d as a t ype

so Java kno ws where to lo o k fo r it. The m yDuke = ne w Duke s() creates an instance with the ne w co mmand
and the Classes co nstructo r Duke s().
In the seco nd case abo ve, Duke s m yDuke = ne w Duke s() bo th declares and creates the instance in o ne
line.
In the next sectio n we'll see the difference between the two cases.

Another Applet for Dukes


We've been to uting the po wer o f o bject-o riented design fo r a while no w, so let's see ho w to take advantage o f
its capabilities by reusing the Dukes class in ano ther Applet. In this Applet we'll create t wo instances o f
Dukes. Make a new Class called T wo Duke sApple t , and re m e m be r t o m ake t he supe rclass
java.apple t .Apple t . Be sure to create this file in the Lesson07/src folder as well.
CODE TO TYPE: Two DukesApplet
import java.applet.Applet;
import java.awt.*;
public class TwoDukesApplet extends Applet {
Dukes myDuke, yourDuke;
// two declarations for Duke instances
String myAction, yourAction;
// each will have their own action
public void init() {
myDuke =new Dukes();
// instantiate first Duke
myAction = myDuke.getActionImage(); // his first action
yourDuke =new Dukes();
yourAction = yourDuke.think();

// instantiate second Duke


// his first action is to think

resize(400,200); //resize the applet window so that we can see both duke
s
}
public void paint(Graphics g) {
Image myChoice = getImage(getDocumentBase(), myAction);
for first Duke
g.drawString(myDuke.getAction(), 10,165);
g.drawString(myDuke.getMessage(), 10,180);
g.drawImage(myChoice, 20, 50, Color.white, this);

// get and show image

Image yourChoice = getImage(getDocumentBase(), yourAction);


image for second Duke
g.drawString(yourDuke.getAction(), 200,165);
g.drawString(yourDuke.getMessage(), 200,180);
g.drawImage(yourChoice, 200, 50, Color.white, this);
}
}

// get and show

Save and Run it.


No w yo u sho uld see two instances o f Duke o n this Applet. No tice that we used re size (4 0 0 ,20 0 ) to make the
Applet big eno ugh so we co uld see bo th Dukes.
As the co urse pro gresses, yo u will implement and change Classes in many different ways. Fo r no w, the go al
is to understand the basics: Classes define variables and metho ds which help to define the Class itself and
specify its capabilities. In the next lesso n we'll write o ur o wn Classes again, and we'll also use so me o f the
classes that Java has written fo r us to make co ding easier.

But fo r right no w, we're exactly where we want to be!


Copyright 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Using the API: Introductory Graphics


When yo u co mplete this lesso n, yo u will be able to :

Lesson Objectives
use the graphics class.
use the java.awt package (abstract windo w to o lkit) that is fo und in the API.

Using Java Provided Classes


In this lesso n we'll fo cus o n using the Graphics class and its capabilities. This will serve two purpo ses: first we'll learn
ho w to do so me drawing, and seco nd we'll learn mo re abo ut using pre-defined classes fro m the Java API.

java.awt.Graphics Class
In mo st o f the Classes we've created so far, we inherited fro m Apple t . To do this, we impo rted using im po rt
java.apple t .Apple t ; so the Java co mpiler co uld find the class and retrieve its inhe rit e d pro perties and
metho ds. Mo st o bject-o riented pro gramming is no t abo ut writing co de fro m scratch, but using co de that
o thers have already written. Java pro vides a large library o f co de, as well as do cumentatio n to help us figure
o ut what's available in that library and ho w to use it. The do cumentatio n is lo cated in the API. (And there's a
handy

link o n the menu to o .)

Yo u might recall that we used the Graphics Class in many o f the Classes we created in earlier lesso ns. In an
Applet, the Graphics area is passe d to the paint (Graphics g) metho d when it gets instantiated. The
Graphics area is where yo u can "draw" o r "print" things. Fo r instance, in o ur Hello Wo rld Applet, we printed
so me text. The Graphics class allo ws us to do stuff like that. In this lesso n, we'll wo rk with the Graphics
and Applet Classes to see so me o f the capabilities they o ffer.
Alright, yo u kno w the drill. St art a ne w pro je ct calle d java1_Le sso n0 8. Just in case, I'll remind yo u ho w
to do it o ne mo re time:
1. Go to the File menu: File | Ne w | J ava Pro je ct .

To
do

2. Give it the name java1_Le sso n0 8.


3. Click Finish.
(If it asks whether yo u'd like to "Open Asso ciated Perspective", say "No "--we want to
keep o ur o wn perspective enviro nment.)

No w start a ne w Class calle d First Line and make the superclass java.apple t .Apple t :
CODE TO TYPE: Simple Applet Using Graphics
import java.awt.*;
import java.applet.Applet;
public class FirstLine extends Applet {
public void paint(Graphics g)
{
g.drawLine(20,10,40,40);
}
}

Run this Applet. Yo u sho uld see a line. I guess that's kind o f co o l, huh? No w play aro und and change the
numbers in the drawline() metho d to see if yo u can get the line to mo ve up fro m left to right.
If there were instance variables o r class variables present, we'd put them either at the beginning o f the class,

If there were instance variables o r class variables present, we'd put them either at the beginning o f the class,
be f o re any metho d definitio ns, o r at the end o f the class af t e r all o f the metho d definitio ns.
In this class there is o nly o ne metho d defined. Metho d definitio ns are easy to find because they will have
parentheses fo r their parameters and then curly brackets to indicate their blo ck o f co de.
One o f the metho ds defined in the FirstLine class is the paint (Graphics g) metho d.
The Graphics g in the argument o f the paint metho d is called the metho d's f o rm al param e t e r. It indicates
that this metho d must be given o r passe d an instance o f a Graphics o bject. The Graphics instance that is
passed to the metho d is called the act ual param e t e r and has been given the variable name o f g. Since g
no w represents the Graphics o bje ct , we can execute "Graphics" actio ns o n it.
As yo u can see fro m this little Applet we made, Graphics o bjects can draw lines. Manipulating pixels enables
us to determine the lo catio n and co lo r o f o ur graphics. To co ntro l lo catio n, we co nsider ho rizo ntal and
vertical o r (x,y) co o rdinates, with (0 ,0 ) being defined as the to p left co rner.

In this example, we drew a line fro m pixel lo catio n (20 ,10 ) to pixel lo catio n (4 0 ,4 0 ). So in the
g.drawline (20 ,10 ,4 0 ,4 0 ) metho d, the first two numbers are the co o rdinates o f the start o f the line and the
seco nd two numbers are the end o f the line.
We see t wo metho ds in the FirstLine class:
1. paint(Graphics g) is a m e t ho d we are de f ining fo r o ur new subclass FirstLine o f the class
Applet. The metho d paint () has o ne fo rmal parameter o f t ype Graphics.
2. drawLine(20,10,40,40) is a pre -de f ine d m e t ho d (altho ugh we can enter any parameters we
wish) o f the class Graphics, o f which g is an inst ance . We are invo king (using o r calling) this
metho d. To do that, we need to lo o k at the API in the Graphics class to see ho w it was defined so
that we kno w its fo rmal parameters and then when we use it, we can pass it the right things.

Using the API


As we've mentio ned, the API co ntains the existing classes Java pro vides fo r pro grammers.
1. Go to the API o pening page here and lo cate the Package s header.

T o do

Note

Even tho ugh we o ften pro vide these links fo r yo u during lesso ns, try to get used to go ing to the
butto n o n the menu bar instead.

Packages are gro upings o f Classes that are related in so me fashio n. These packages are put into different
dire ct o rie s o r f o lde rs fo r us to access, but in o rder fo r Java to find them when we're running o ur pro grams,
they have gro uped them into what they call package s.
The packages that we'll find particularly useful no w are:
java.applet
java.awt
java.awt.event
java.lang

But there are many mo re. In this lesso n, we'll mainly fo cus o n o ne class that lives in the java.awt package.
(By the way, awt stands fo r abst ract windo w t o o lkit .)
In the API page that o pened:

1. Click o n the java.awt link.

T o do

2. Scro ll do wn until yo u see the header Class Sum m ary.


3. Scro ll do wn to lo cate the Graphics Class and then click o n it.

Yo u sho uld get a page that lo o ks like this, altho ugh yo u may see mo re frames fo r o ther packages and
classes o n the left. Let's take a clo ser lo o k at so me impo rtant aspects sho wn in the API. Keep o ne o f the
bro wsers with the Graphics class o pen so we can co mpare.

In the to p left co rner, the API tells us that the Graphics class is in the java.awt package. No tice Classes are
named with the package name first, and that package names are separated with perio ds and start with lo wer
case letters. Also no te that Classes always start with capital letters. That makes it easy to differentiate
between the package and the class.
The API also displays an inhe rit ance t re e :

This indicates that Graphics is an Object.


It also indicates which package each o f the classes is in (Object is in java.lang and Graphics is in java.awt).
Remember fro m Lesso n 2 that e ve ry o bje ct in Java inherits fro m the class java.lang.Object. That's o ne
reaso n yo u never need to impo rt the package java.lang. Because it's always needed, Java impo rts it by
default.
Next the API tells us all o f the Classes that are pro vided in Java that have the Graphics class as a pare nt (a
superclass).

In the API page fo r the Graphics class:

1. Click o n the De bugGraphics Subclass link.


2. No te its inheritance chain. Its Superclass is java.awt.Graphics.

T o do

3. Go back to the Graphics page.


4. Click o n the Graphics2D Subclass link.
5. No te its inheritance chain.

To reiterate and make abso lutely certain this will be emblazened into yo ur memo ry banks fo r all eternity,
inheritance is an impo rtant part o f o bject-o riented pro gramming because it allo ws us to use Classes that
have already been written.
Finally, let's lo o k at the public abstract class Graphics extends Object. This is the first line o f co de
that defines the class Graphics. It starts the definitio n o f the Class and tells us where this class belo ngs in an
inheritance tree. It tells us the mo st spe cif ic class fro m which it inherits. Yo u can see all o f the o ther Classes
that it inherits fro m the descriptio n o f this Class in the API.

Note

If yo u inherit fro m a specific Class, yo u inherit all o f the ance st o rs (the entire inheritance chain)
as well.

Let's take a lo o k at o ther stuff the API o ffers us fo r the Graphics class.

To
do

1. Scro ll do wn the API page until yo u see a Header that says Co nst ruct o r
Sum m ary.

It sho uld lo o k like this:

Co nstructo rs are metho ds as well, but they are special because we use them to create an instance o f the
Class (instantiatio n). And o f co urse, the Co nstructo r has the same name as the Class.
In the Me t ho d Sum m ary yo u see m any metho ds that are defined in the Graphics class. Except fo r the
Co nstructo r metho d, all metho ds begin with lo wer-case letters.

To
do

1. Scro ll do wn thro ugh the metho ds o f the Graphics class to get a feel fo r what's
available.

The mo st co mmo nly used Graphics metho ds are draw and f ill. Yo u can find o ut mo re abo ut each metho d
and its usage by clicking o n them.

To
do

1. Go to the drawLine metho d--drawLine(int x1, int y1, int x2, int y2)--in the API
Graphics listing and click o n it.

Methods, Parameters (or Arguments), and the Dot Operator


No w let's lo o k at the specificatio ns o f the drawLine metho d in o ur class FirstLine. In defining the metho d
paint () fo r Applets, Java specifies that its metho d has a parameter that is passe d. This parameter is a
Graphics o bject (yo u can see fo r yo urself in the API). In o ur FirstLine class co de fo r the paint metho d, we
name this Graphics o bject g. Since we are defining the metho d, we co uld name the variable that ho lds the
o bject whatever we like. But o nce yo u name it, yo u'll have to use the same name thro ugho ut yo ur metho d
definitio n. This isn't hard to do here tho ugh, because we o nly have o ne line so far.
Because the paint () metho d is present fo r all Apple t , the Graphics area is always created and given to us
thro ugh the Applet. This is ano ther example o f inheritance. We have inherited all o f the traits o f Applets and the
Applet has pro vided this Graphics area by passing it to the paint metho d every time o ur Applet is displayed
and repainted.
We invo ke d o r calle d the Graphics drawLine() metho d by typing g.drawLine (20 ,10 ,4 0 ,4 0 );. This line uses
the do t o pe rat o r o f Java. In fro nt o f a do t is the o bje ct and after the do t is either o ne o f that o bject's
variable s/f ie lds o r a call to o ne o f that o bject's m e t ho ds. If yo u see parentheses, it is calling a metho d. If
yo u do no t see parentheses, it is calling a variable. In this example, we are telling Java to go to the o bje ct we
named g and to use o ne o f its metho ds called drawLine (). Inside the parentheses are the "actual
parameters" we want Java to use.
To make sure we used this metho d co rrectly, we co mpare o ur metho d call and its act ual param e t e rs to the
drawLine () metho d specificatio n and the f o rm al param e t e rs in the API.
On the API page, fo r the metho d drawLine() we see:

This definitio n lets us kno w that if we have a Graphics o bject, we can use the metho d drawLine() if we pass it
fo ur integers (int). The metho d drawLine() will then assign the fo ur integers as stated. The first two values will
be (x,y) fo r the first po int in the line, and the seco nd two values will be the (x,y) fo r the seco nd po int. Here are a
co uple o f alternate illustratio ns o f parameters:
public abstract vo id drawLine(int x1,int y1,int x2,int y2) The metho d definitio n line (so metimes called
the metho d's signat ure ) pro vides f o rm al param e t e rs.
g.drawLine(20 ,10 ,40 ,40 ); Here we see the use o f specific numbers to send to the metho d fo r it to
use, hence it pro vides what are called act ual param e t e rs.
We use the API to find metho d definitio ns and make sure we send the pro per type and number o f parameters.

Sequencing
Let's use so me o f the metho ds in the Graphics class to draw so mething in an Applet.
We'll be using a pro gramming construct called se que ncing as well. Sequencing means that if yo u give Java
a list o f things to do , it will do them in o rder, o ne after ano ther. After we get Java to draw o ur first line, we'll
have it do even mo re wo rk fo r us.
Start ano ther class called MyPicture that extends Applet:
CODE TO TYPE:
import java.awt.*;
import java.applet.Applet;
public class MyPicture extends Applet {
public void init()
{
this.setBackground(Color.lightGray);
}
public void paint(Graphics g)
{
g.drawLine(0,0,100,100);
g.setColor(Color.RED); // make a red ball
g.fillOval(45, 15, 40, 40);
g.setColor(Color.GREEN); // a couple of support beams
g.fillRect(5, 5, 4, 95);
g.fillRect(65, 65, 4, 35);
g.setColor(Color.BLACK);
// a landing strip
g.drawLine(100,100,200,100);
}
}
Run it.
There's lo ts fo r us to check o ut, even in this simple pro gram. First, an Applet always starts by having its init
metho d called and then its paint metho d. Once inside the paint metho d, we see the use o f line
se que ncing, particularly with use o f the Graphics o bject g. No tice the change o f co lo r in the co de and Applet,
and also that the co lo rs are specified by typing Co lo r.lightGray, Co lo r.Red, and so o n.
1. Go to the Graphics API and read the specificatio ns o f the metho ds that start with:
draw (e.g. drawOval, drawPo lygo n, drawSt ring)

T o do

fill (e.g. f illRe ct , f illOval, f illArc)


get (e.g. ge t Co lo r)

T he java.awt.Color Class
Shapes in a Graphics o bject can be filled in o nce a co lo r is specified. By default the co lo r o f the graphics
"pen" is black. The class java.awt.Co lo r pro vides a list o f co lo r po ssibilities.
Here are so me o f the Co lo r classes used in the MyPicture.java class:
this.setBackgro und(Co lo r.lightGray);
g.setCo lo r(Co lo r.red);
Lo o k at the MyPicture.java class to check o ut these "metho d calls" in detail:

t his.se t Backgro und(Co lo r.light Gray); No tice the wo rd t his within the co de. Because that line
is within the init() metho d o f a class that is an Applet, the t his means that yo u are telling t his
Apple t to set its backgro und. Thus we wo uld lo o k fo r the metho d in the Applet class.
g.se t Co lo r(Co lo r.re d); These metho d calls are all in the paint metho d o f the Applet. No te that
before the do t o perato r there is a g. g is a Graphics o bject/instance, so we are telling Java that we
want to use the Graphics metho d o f se t Co lo r() o n o ur g o bject.
To find mo re abo ut se t Backgro und(Co lo r.light Gray), go to the Applet API and lo o k fo r the metho d
se t Backgro und(Co lo r c). Applet inherits backgro und co lo r fro m Co m po ne nt . Lo o k in the m e t ho d
inhe rit ance se ct io n -- abo ut a third o f the way do wn the page yo u'll see:

To find o ut mo re abo ut se t Co lo r(Co lo r.re d), go to the Graphics API and lo o k at its metho ds. Click o n
se t Co lo r(Co lo r c) fo r mo re detail.
Let's discuss the keywo rd t his a bit mo re. When we write the definitio n o f a Class, we do n't kno w the name
the user will give to the instance when they use o ur class. Tho usands o f pro grammers might end up using the
class, each o ne giving a different name fo r each instance. That's why we use the re se rve d wo rd this within
the co de o f a class definitio n: to indicate that we are telling this object (the o bject that we are currently using) to
invo ke the metho d given. In the abo ve example, we are telling the instance o f the MyPicture Applet to have a
backgro und co lo r o f lightGray with the line: this.setBackground(Color.lightGray);.
Similarly, when we have an instance o f an o bject, so metimes we'll want to tell its pare nt to do so mething.
Since yo u wo n't always kno w the parent o f every instance inside the definitio n o f the class co de, Java uses
the re se rve d wo rd super. So , this means "this o ne," "me," while super means "this instance class's
parent."
Okay, back to o ur discussio n o f Co lo r. Click o n the Co lo r API. Scro ll do wn the Co lo r API page to see the
Fie ld Sum m ary. No w we'll get to see so me Class Variable s.

Note

T o do

In the API, Java uses the term Fie lds fo r the Instance and Class Variable s.

1. Scro ll do wn to the Fie ld Sum m ary fo r Co lo r.


2. Lo o k at the left co lumn.

This is a list o f the Variables that the class Co lo r pro vides fo r us. Yo u can see the two wo rds st at ic Co lo r
thro ugho ut the list.

Note

The re se rve d wo rd o f st at ic is a m o dif ie r fo r the Field and indicates that the Variable (o r
Metho d) is a Class Variable (o r a Class Me t ho d when applied to metho ds). Static variables
will be co vered in a later lesso n.

Recall that Classes have two co mpo nents: Variable s and Me t ho ds. Ho wever, they each co me in two fo rms:
Inst ance and Class. So these are the fo ur co mbinatio ns available:
Instance Variables
Class Variables
Instance Metho ds
Class Metho ds
That's it! Once yo u've go t this co ncept do wn, it's a who le lo t easier to read co de.
So what are the differences between Instance Variables and Class Variables? Here are so me impo rtant o nes:
A Class Variable is shared by all o f the instances in a Class. Fo r example, all members o f the

A Class Variable is shared by all o f the instances in a Class. Fo r example, all members o f the
Class "Human" have t wo eyes. But the co lo r o f eyes changes fro m o ne human to the next. So
numberOfEyes wo uld be a Class Variable set to 2 in the Human class, but co lo rOfEyes wo uld be
an Inst ance Variable that changes with each instance.
Because the Class Variables are shared by all in the Class, their values are no t sto red in separate
places in the co mputer's memo ry. Values fo r Class Variables are in a single lo catio n in memo ry.
This means that if the value changes fo r o ne instance, it changes fo r all instances o f the Class.
A Class Variable (o r Metho d) can be calle d fro m e it he r the Class, o r an instance o f the Class. Fo r
example, the value o f the variable BLACK in the Co lo r class is expected to be the same whenever
it is called, thus it do es no t need to be "created" each time it is used. This makes us happy. The
Co lo r class will be used quite o ften, and it wo uld be a pain, fr example, to have to make a new
instance o f Co lo r every time we wanted to get the co lo r black.
Let's lo o k at the way we specified Co lo rs in o ur co de: Co lo r.light Gray o r Co lo r.RED.
No te that we have a do t o pe rat o r here, and that after the do t there can be either a metho d o r a variable. And
we kno w it's no t a metho d because metho ds always have parentheses.
Recall that co nventio n dictates that Classes begin with capital letters. Lo o k at ho w we accessed the co lo rs:
Co lo r.RED
Here we're accessing Co lo r's variable RED thro ugh its class name Co lo r. In o ther wo rds we didn't create an
instance like this: Co lo r myco lo r = new Co lo r(255,0 ,0 ); and call myCo lo r.RED, instead we simply called
Co lo r.RED.
We are able do this because the variable RED is a Class Variable.
We kno w that we can do this here because the ke ywo rd st at ic is in the Class's specificatio n o f the variable
(lo o k it up in the API!). We'll co ver static variables mo re in Lesso n 14, but basically static variables are
declared static because they aren't expected to change and we can access them thro ugh their Class name
instead o f their instance name (they aren't instance dependent instance variables.)
So what else was in the Fie ld Sum m ary fo r the class Co lo r?
1. The variables tell us that they are st at ic (which always means Class variables), and they also co ntain the
wo rd "Co lo r" and a link to the Co lo r class. This is because each o f the Class Variables in the class Co lo r is
Co lo rs:
black is a Co lo r
BLACK is a Co lo r
blue is a Co lo r
BLUE is a Co lo r
The descriptio n o f the Fields/Variables is telling yo u the t ype o f Object the Variable is.
2. Each o f the Class variables in the class Co lo r is either in all CAPITAL o r all lo wer-case letters.
Lo o k at so me o f the metho ds o f the Class Co lo r. Yo u can make a co lo r lighter o r darker using these
metho ds. Fo r example:
Co lo r.red.darker();
Here Java go es to the Co lo r class, gets the Class Variable re d, then invo kes the metho d darke r() o n that
Co lo r.
But there is so mething tricky go ing o n here. It turns o ut that Co lo r.RED, is a Class variable AND an Object.
That's because the definitio n o f RED in the Class Co lo r is Co lo r RED = ne w Co lo r(25 5 ,0 ,0 );, so RED is an
instance o f the Co lo r class. And so , we can call things like Co lo r.re d.darke r();, since Co lo r.red is a Co lo r
o bject itself. We co uld also simply call Co lo r no se Co lo r = ne w Co lo r(25 5 ,0 ,0 ); and then call
no se Co lo r.darke r(); to make it darker.

T o do

1. Ope n the MyPict ure class and Run it (do n't clo se it).
2. Edit the MyPict ure class's paint metho d as sho wn belo w in blue .

CODE TO EDIT
import java.awt.*;
import java.applet.Applet;
public class MyPicture extends Applet {
public void init()
{
this.setBackground(Color.lightGray.darker());
}
public void paint(Graphics g)
{
g.drawLine(0,0,100,100);
g.setColor(Color.RED.darker());
g.fillOval(45, 15, 40, 40);

// make a red ball

g.setColor(Color.GREEN); // a couple of support beams


g.fillRect(5, 5, 4, 95);
g.fillRect(65, 65, 4, 35);
g.setColor(Color.BLACK);
// a landing strip
g.drawLine(100,100,200,100);
}
}
Save and Run it. Co mpare the two Applets' co lo rs.
Great wo rk so far. We're really making pro gress. In the next lesso n, we'll expand o ur artistic palette to include even
mo re Java capabilities. See yo u there!
Copyright 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Drawing with Graphics


When yo u co mplete this lesso n, yo u will be able to :

Lesson Objectives
lo cate specific metho ds in the API to create a drawing.
use the Graphics Class to draw.

Making Pictures
Back to Graphics
In this sectio n we'll use the Graphics Class to make drawings. First, let's make an Applet we can use to test
o ur drawings.
1. Make a new pro ject fo r Lesso n 9 : File | Ne w | J ava Pro je ct .
2. Name the Pro ject java1_Le sso n0 9 .
3. Click Finish. (If "Open Asso ciated Perspective" appears, click "No ." We want to keep o ur o wn
perspective enviro nment.)
4. Make an Applet in this pro ject called DrawT e st .
The co de fo r the Applet is fairly simple:
CODE TO TYPE: DrawTest
import java.applet.*;
import java.awt.*;
public class DrawTest extends Applet
{
public void init()
{
setBackground(Color.cyan);
}
public void paint(Graphics g)
{
// empty for now until we have made code of images to draw
}
}
Okay, no w we need to add a Class that draws so mething. This first drawing will use o nly o vals and lines.
Let's try to draw Cart m an fro m the TV sho w So uth Park, using o nly the primitive shapes available in the Java
API.

1. Lo o k in the Graphics API fo r so me metho ds that draw.


2. Go to the Graphics API listing o f metho ds fo r the f illOval() metho d.
3. Click o n the f illOval() link there.
Yo u sho uld see this:

So metimes the API do esn't pro vide an exact metho d to help us execute a task, so we have to wo rk aro und it,
but in this case it do es. fo r o ur purpo se here, a circle IS co nsidered a type o f o val. A circle is in essence a
symmetrical o val, an o val that has the same height and width. So in o rder to draw circles, we use the same
metho ds that make o vals.

Alright, let's get to wo rk! In the java1_Lesso n0 9 pro ject, cre at e a ne w Class calle d Cart m an.

CODE TO TYPE: Cartman


import java.awt.*;
public class Cartman {
Graphics g;
can use it

// make the Graphics area an instance variable so the methods

public Cartman(Graphics graph)


// the class Constructor
{
this.g = graph; // give the graph instance to the Instance Variable we na
med g
}
public void drawMe()
{
g.setColor(Color.PINK);
g.fillOval(10,30,180,150); //Cartman's face
g.setColor(Color.white);
g.fillOval(50,66,35,53); //Cartman's eyes
g.fillOval(78,66,35,53);
g.setColor(Color.black); //Cartman's eyeballs
g.fillOval(63,86,10,10);
g.fillOval(90,86,10,10);
g.setColor(Color.black); //Cartman's mouth
int [] xValues = {56,89,109};
int [] yValues = {140,150,140};
g.fillPolygon(xValues, yValues, 3);
}
}

// end drawMe method


// end Cartman class

Save it.
Okay, no w we need the Applet to see this class. Go back to yo ur DrawTest.java file. Edit the paint metho d yo u
find there by adding the co de belo w:
CODE TO TYPE
import java.applet.*;
import java.awt.*;
public class DrawTest extends Applet
{
public void init()
{
setBackground(Color.cyan);
}
public void paint(Graphics g)
{
Cartman myCartman = new Cartman(g);
myCartman.drawMe();
}
}

Run it. No t a bad likeness if yo u ask me. In the pro jects fo r this lesso n, yo u'll make him lo o k even mo re
like Cartman.
No w let's take a lo o k at the f illPo lygo n() metho d in Graphics in the API. No tice that this metho d is
o ve rlo ade d - lo o k at its two signatures:

Ho ld o n a minute. There are t wo fillPo lygo n() metho ds? In the previo us lesso n we mentio ned the co ncept o f
po lym o rphism --that so metimes the same name is used in different places. On o ccasio n, a metho d might
o ve rride its parent. No w in this Class we see an example o f ano ther impo rtant fo rm o f po lymo rphism called
o ve rlo ad.
Overlo ading is when a specific class has mo re than o ne metho d with the same name. Hmm, this so unds like
it co uld get tricky. But Java figures o ut which o ne to use by reading the metho d's f ull signat ure . The
signature is a metho d's definitio n and is determined by its name and the number and types o f parameters it
takes. Yo u can have metho ds with the same name, and even the same parameters, but they'll all have
different signatures.
A signat ure o f a metho d is much like the signature o f a human; each signature is unique. As such, in Java, a
signature can be used to identify a metho d, then decide which o ne to use. To acco mplish this task, Java:
Indentifies the type o f class calling the metho d (i.e., the o bject in fro nt o f the do t o perato r -- like g in
g.drawLine).
Observes the name o f the metho d.
Observes the num be r and the t ype o f parameters (if there is mo re than o ne metho d with the
same name).
Ensures that the pro per values fo r Java have been passed. In o ther wo rds, the values passed
(actual parameters) are co nsistent with tho se defined in the class (fo rmal parameters).
So lo o king at the API again, the f illPo lygo n() metho d takes 3 parameters (int [] xpo int s, int [] ypo int s,
int npo int s) o r 1 parameter (Po lygo n p). In the Cartman example, we're using the metho d that takes 3
parameters. If we had a Po lygo n o bject to pass to it, we co uld use the metho d with 1 parameter--in fact we'll
try that a bit later, but fo r no w let's go o ver what we've do ne here using the metho d that takes 3 parameters.
Yo u can tell that the first 2 parameters are sets o f integers because they take an integer array int[] (Arrays are
sets and are indicated by square brackets. We'll study arrays in great detail in the next Java co urse).
Let's co nsider an example. Suppo se yo u wish to fill these 4 po ints in the po lygo n: (15 ,20 ), (17 0 ,39 ),
(16 0 ,10 0 ) and (4 0 ,15 0 ). The shape wo uld be:

Go to the Graphics class and lo o k at the spec fo r "drawPo lygo n(int[] xPo ints, int[] yPo ints, int nPo ints)." See

ho w it indicates that the first parameter is an array o f x co o rdinates?


The array o f x co o rdinates wo uld lo o k like this: [15 ,17 0 ,16 0 ,4 0 ]
The array o f y co o rdinates wo uld lo o k like this: [20 ,39 ,10 0 ,15 0 ]
The metho d call to a graphics o bject g wo uld be:
OBSERVE:
int [] xValues = {15,170,160,40}; // declare the arrays
int [] yValues = {20,39,100,150};;
g.fillPolygon(xValues, yValues, 4);
The number 4 in the argument o f the f illPo lygo n() metho d is the number o f po ints in the po lygo n we're
drawing.
No w let's get back to o ur example. In o ur example we drew a triangle fo r Cartman's mo uth. We passed the
f illPo lygo n() metho d two integer arrays ( 3 xValues and 3 yValues) and passed the number o f po ints (3). To
sho w the po lymo rphism o f the f illPo lygo n() metho d, let's create a Po lygo n o bject and pass that to
f illPo lygo n(). Change the Cartman class as fo llo ws:
Change the co de in blue in the Cartman Class
import java.awt.*;
public class Cartman {
Graphics g;
an use it

// make the Graphics area an instance variable so the methods c

public Cartman(Graphics graph)


// the class Constructor
{
this.g = graph; // give the graph instance to the Instance Variable we nam
ed g
}
public void drawMe()
{
g.setColor(Color.PINK);
g.fillOval(10,30,180,150); //Cartman's face
g.setColor(Color.white);
g.fillOval(50,66,35,53); //Cartman's eyes
g.fillOval(78,66,35,53);
g.setColor(Color.black); //Cartman's eyeballs
g.fillOval(63,86,10,10);
g.fillOval(90,86,10,10);
g.setColor(Color.black); //Cartman's mouth
int [] xValues = {56,89,109};
int [] yValues = {140,150,140};
Polygon shapeThing = new Polygon(xValues, yValues, 3);
g.fillPolygon(shapeThing);
}
}

// end drawMe method


// end Cartman class

Save and Run the Applet again.


Yo u sho uld see exactly the same thing. The o nly difference in the co de here is that we passed f illPo lygo n()
a Po lygo n o bject. No t much o f a leap, but nevertheless an example o f po lymo rphism. We'll see many mo re
examples o f this in the near future.
So to reiterate, as we are pro ne to do , the central ideas o f o bject-o riented pro gramming are:

Inheritance
Po lymo rphism
Encapsulatio n
These characteristics allo w us to use the API fo r large po rtio ns o f o ur pro gramming. As the co urse co ntinues,
we'll see mo re o f these principles o f o bject-o riented design in actio n.
Ho pefully the API is fast beco ming yo ur new best friend. Officially API is an acro nym fo r Applicat io n
Pro gram m ing Int e rf ace , but we can think o f so me better wo rds! Let me try...
Abso lute Pro ductivity Increase
Archived Pro gramming Intelligence
Available Po tential Ideas
Avo id Pro gram Illiteracy
Aro use Pro grammer Insight
All Packed In

Yo u're do ing great!


Copyright 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Methods and Method Invocation


When yo u co mplete this lesso n, yo u will be able to :

Lesson Objectives
create and use yo ur o wn metho ds, no t fo und in the API.
In this lesso n we'll get a chance to trace the steps o f an o bject-o riented pro gram as it runs.

Methods
There are o nly two things in a Class:
Fie lds (data types)
Me t ho ds
They are o ften called the Class Me m be rs.
The two kinds o f Fie lds (data types and variables to access these data types) that Java allo ws are:
Obje ct s (instances o f Classes) and
Prim it ive Dat a T ype s (numbers, characters, bo o lean)
But right no w, we're go ing to fo cus o n Me t ho ds. Specifically we want to learn ho w they're written, and ho w and when
they're invo ked.

Creating and Using Methods


There are two ways to o btain metho ds to use when yo u're creating o bject-o riented pro grams. Yo u can:
Write yo ur o wn.
Impo rt them fro m existing Classes.
We've been invoking o r calling metho ds fro m Classes we fo und in the API since Lesso n 1. Fo r example, we
used g.drawSt ring(" He llo Wo rld" , 5 0 , 5 0 ); by invo king the metho d drawSt ring() o n the instance g o f the
class Graphics.
Usually, a Java pro gram co nsists o f bo th calls to metho ds fro m the API, and calls to metho ds that a
pro grammer has written specifically fo r her pro ject.
Belo w is co de fo r a Class named T riangle ClassDe m o . The Graphics Class has a lo t o f metho ds available
to draw vario us geo metric o bjects, but no ne fo r triangles. We kno w that drawing a triangle just means to draw
three lines, but if we wanted to draw 6 triangles, it wo uld be easier to make 6 calls to a drawTriangle metho d
than 18 calls to a drawLine metho d where we have to think abo ut where the lines meet each time!
If the API isn't go ing to hand us an easy metho d, that's fine. We can just make o ne o urselves. The API can't do
it all, but we can.
Make a new pro ject fo r Lesso n 10 called java1_Le sso n10 . Also make a new class called
T riangle ClassDe m o that has java.applet.Applet as its superclass.

CODE TO TYPE: Triangles


import java.awt.*;
import java.applet.Applet;
public class TriangleClassDemo extends Applet {
public void paint(Graphics g) {
this.drawTriangle(g, 80, 120, 100, 110);
}
private void drawTriangle(Graphics g, int bottomX, int bottomY, int base, int
height){
g.drawLine(bottomX, bottomY, bottomX+base, bottomY);
g.drawLine(bottomX+base, bottomY, bottomX+base/2, bottomY-height);
g.drawLine(bottomX+base/2, bottomY-height, bottomX, bottomY);
}
}
Run it.
Isn't that a nice triangle?
Let's lo o k at the two metho ds that we see defined in the T riangle ClassDe m o class: paint () and
drawT riangle ()
The first metho d we see in the class bo dy is paint (Graphics g). By no w we're pretty familiar with paint (), so
the o nly co ncept we'll review no w is the use o f this in the call. Take a lo o k at this co de:
this.drawT riangle (g, 80 , 120 , 10 0 , 110 );
We've seen the use o f this with Inst ance Variable s befo re. In Lesso n 4 we to o k the graph o bject that was
passed to us in the paint () metho d and gave it to the Instance Variable g this.g = graph;
The this in fro nt o f the variable indicates that it's an IV (Instance Variable) o r a CV (Class Variable) o f the
instance o f t his particular Class.
We also saw its use in Me t ho ds when we set the backgro und co lo r o f o ur Applet in Lesso n 4:
t his.se t Backgro und(Co lo r.light Gray);
Its use here is similar. Using this, we are saying that there is a metho d drawT riangle ( ) in t his class (o r in a
class fro m which it inherits) and we want to invo ke it. Sure eno ugh, if yo u lo o k at the next defined metho d in
o ur class, there it is:
privat e vo id drawT riangle (Graphics g, int bo t t o m X, int bo t t o m Y, int base , int he ight )

Note

The use o f the keywo rd this in fro nt o f the do t o perato r fo r metho d calls within a given class is
o ptio nal.

Edit the T riangle ClassDe m o class's paint () metho d as sho wn:

CODE TO TYPE
import java.awt.*;
import java.applet.Applet;
public class TriangleClassDemo extends Applet {
public void paint(Graphics g) {
this.drawTriangle(g, 80, 120, 100, 110);
drawTriangle(g, 125, 140, 60, 70);
// demonstrating we don't really NEED "this"
}
private void drawTriangle(Graphics g, int bottomX, int bottomY, int base, int
height){
g.drawLine(bottomX, bottomY, bottomX+base, bottomY);
g.drawLine(bottomX+base, bottomY, bottomX+base/2, bottomY-height);
g.drawLine(bottomX+base/2, bottomY-height, bottomX, bottomY);
}
}
Run it.

T ip

If a Fie ld o r Me t ho d is accessed without a do t o perato r (i.e., with no instance name preceding it),
then the Class Me m be r being accessed is always o ne o f the curre nt class or o ne o f its
ancesto rs.

The o nly o ther metho d defined in this class is o ne we wro te o urselves using metho d calls to drawLine in
Graphics. It has this declaratio n:
OBSERVE:
private void drawTriangle(Graphics g, int bottomX, int bottomY, int base, int he
ight){
g.drawLine(bottomX, bottomY, bottomX+base, bottomY);
g.drawLine(bottomX+base, bottomY, bottomX+base/2, bottomY-height);
g.drawLine(bottomX+base/2, bottomY-height, bottomX, bottomY);
}
The required elements o f a metho d declaratio n (mo st o f which are o n the first line) are:
1. The metho d's re t urn t ype --in this example, the return type is vo id which means no thing is
returned. (We'll discuss return type mo re later.)
2. The metho d's name--in this example, it's drawT riangle .
3. A pair o f pare nt he se s ( )--in this example, (Graphics g, int bo tto mX, int bo tto mY, int base, int
height).
4. A bo dy be t we e n brace s { } --in this example, the bo dy includes the three drawLine () calls.
In the bo dy o f the drawTriangle metho d, the three lines fo r o ur triangle are being drawn. Our metho d draws an
iso sce le s t riangle so it will have a base, a height, and equal sides. The fo rmal parameters requested
(Graphics g, int bo t t o m X, int bo t t o m Y, int base , int he ight ) pro vide:
The Graphics area o n which to draw the lines--Graphics g
The (x,y) lo catio n fo r the bo tto m left co rner o f the triangle--int bo t t o m X, int bo t t o m Y
The length o f the base (bo tto m) and the length o f the height--int base , int he ight
This diagram sho ws ho w the parameters passed will be used to draw the lines that make the triangle:

In the next sectio n we'll begin o ur trace.

T racing method calls


Recall that Apple t s are started by the bro wser in which they're embedded. The bro wser gets the Apple t
co de, calls its init () and st art () metho ds (if they've been defined; o therwise it inherits these metho ds fro m
its superclasses). Then the Applet's paint (Graphics g) metho d is called.
Since this particular Applet do es no t have specified init and start metho ds, it inherits them fro m its
supe rclass Apple t and then calls o ur paint (Graphics g) metho d.
No te that the paint (Graphics g) metho d is specified as public:
public vo id paint (Graphics g) {
No te also that the drawT riangle ( ) metho d is specified as privat e :
privat e vo id drawT riangle (Graphics g, int bo t t o m X, int bo t t o m Y, int base , int he ight ){
So why do es paint () have to be public yo u ask?
When a metho d is go ing to be called fro m outside o f an instance o f the Class itself, it must be made
accessible to o thers. Its pe rm issio n must be made public. This Applet's paint metho d is called fro m the
bro wser so it needs to be accessible to the public.
When yo u want a metho d to be accessible o nly f ro m wit hin an inst ance o f t he Class (like when yo u use
this), yo u make the permissio n mo difier o f the metho d privat e . Currently, o ur o wn metho d o f paint is calling
this metho d and we do no t expect any o ther Class instances to use o ur drawT riangle metho d, so we made
it privat e .
In an earlier lesso n, we saw the use o f public and privat e when we discussed accesso rs and mutato rs.
Permissio ns are an impo rtant to o l fo r maintaining the integrity, usefulness, and encapsulatio n o f Classes,
Fields, and Metho ds. But let's no t get distracted no w, just when we're abo ut to feel the POWER o f metho d
writing!

So far, the T riangle ClassDe m o Applet has been started and the paint metho d has been called. Inside the
paint metho d bo dy (between the {} ) there was o ne line, then we added ano ther to demo nstrate that we can
use this o r no t.
When Java runs into this statement:
t his.drawT riangle (g, 80 , 120 , 10 0 , 110 );
...it sees this in fro nt o f the do t o perato r, so it kno ws to lo o k inside the class to find the metho d that yo u want it
to run. Java finds the declaratio n o f the metho d and matches the actual parameters in the metho d call to the
fo rmal parameters o f the metho d declaratio n. Here's a visual representatio n o f what's happening:

The actual parameters' types match all o f the fo rmal parameters' types, so Java passes the values (a
reference to the g o bject):
g to g
80 to bo t t o m X
120 to bo t t o m Y
10 0 to base
110 to he ight
Pro gramming languages pass metho d parameters in two ways:
By value : Primitive data types are passed giving the value o f the variable, no t the address o f the
variable.
Changing the value inside the metho d will no t change anything o utside the metho d.
By re f e re nce : Object variables are passed by giving the addre ss o f the instance po inted to by the
variable.
So if yo u change variables o f the o bject within the metho d, it changes them o utside the sco pe o f
the metho d to o ,
because yo u gave the metho d the actual lo catio n o f the o bject's info rmatio n.

WARNING

When o bjects are passed to a metho d and the metho d returns, the passed-in reference
still references the same o bject as befo re. Ho wever, the values o f the o bject's fields may
be changed in the metho d.

So , Java started the Applet, go t into the paint metho d, then the paint metho d immediately sent us to the
drawTriangle metho d.
Hmm. Wo uld it make a difference if in the co de fo r o ur class, we switched the two metho d definitio ns? Do es
paint have to be defined first since it is used first? Let's find o ut.
Mo ve the blo ck o f co de that defines the paint () metho d so that it fo llo ws the drawTriangle metho d's bo dy, but
is be f o re the clo sing } o f the entire class as sho wn belo w:
CODE TO EDIT
import java.awt.*;
import java.applet.Applet;
public class TriangleClassDemo extends Applet {
private void drawTriangle(Graphics g, int bottomX, int bottomY, int base, int
height){
g.drawLine(bottomX, bottomY, bottomX+base, bottomY);
g.drawLine(bottomX+base, bottomY, bottomX+base/2, bottomY-height);
g.drawLine(bottomX+base/2, bottomY-height, bottomX, bottomY);
}
public void paint(Graphics g) {
this.drawTriangle(g, 80, 120, 100, 110);
drawTriangle(g, 125, 140, 60, 70);
}
}
Run it. If yo u placed everything acco rding to the instructio ns, it sho uldn't have made any difference at all to

the result.

Note

The o rder in which the metho ds are defined within a class is irrelevant. It's the o rder in which
they're invo ke d that co unts.

No w that we are within the drawT riangle ( ) metho d, the first thing Java sees is ano ther metho d call:
g.drawLine (bo t t o m X, bo t t o m Y, bo t t o m X+base , bo t t o m Y); This time tho ugh, the instance variable in
fro nt o f the metho d call is no t this, but g. Since g is o f type Graphics, Java go es to the Graphics class next
to see if it has a metho d defined that matches the actual parameters in the call. Success.

Sweet. Because these are all int (integers), Java will give the value o f the actual parameter variables to the
metho d parameters:
x1 = bo tto mX
y1 = bo tto mY
x2 = bo tto mX + base
y2 = bo tto mY
No tice that the variable nam e s yo u use in the actual call do n't have to match the fo rmal specificatio ns'
names. The names do n't matter because (fo r primitive data types) it's the value o f the variable being passed.
Also , when yo u pass Objects, yo u are passing the address o f the variable, but an address can have mo re
than o ne name. So metimes this can cause undesired side-effects when mo re than o ne variable po ints to the
same o bject.
When Java sees the metho d call g.drawLine (bo t t o m X, bo t t o m Y, bo t t o m X+base , bo t t o m Y); it go es
to the Graphics class and its implementatio n o f drawLine ( ), and then executes that metho d.
When that line o f co de is finished, Java go es to the next g.drawLine(bo tto mX+base, bo tto mY,
bo tto mX+base/2, bo tto mY-height); and matches up its parameters, then go es to the Graphics class and its
implementatio n o f drawLine ( ) and executes that metho d.
Then Java executes that entire pro cess again fo r the metho d call g.drawLine(bo tto mX+base/2, bo tto mYheight, bo tto mX, bo tto mY);
When Java sees it's finished with the drawT riangle ( ) metho d, it go es back to the o riginal metho d that called
it, the paint ( ) metho d. Since paint ( ) has no thing else in it, Java is do ne. If yo u didn't remo ve the seco nd
call to drawT riangle ( ) tho ugh, Java wo uld start the who le pro cess again.
So far so go o d. Keep go ing, yo u're do ing a great jo b!
Copyright 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Writing Classes - Building With Methods


When yo u co mplete this lesso n, yo u will be able to :

Lesson Objectives
declare a metho d using the six required co mments in o rder.
use lo cal variables, rather than instance variables.
define a metho d's return type.

More on Methods
Local Variables
In the last lesso n, the parameters inside the drawTriangle metho d may have been a little hard to read,
especially in the drawLine () metho ds:
g.drawLine(bo tto mX+base, bo tto mY, bo tto mX+base/2, bo tto mY-height);
We generally think o f triangles as 3 lines co nnecting 3 po ints, no t so much a set o f parameters like we've
been given here.
So let's use the parameters passed to us (g, bo tto mX, bo tto mY, base, and height) to create the 3 po ints o f the
triangle before using the drawLine ( ) metho d.
We'll edit o ur co de to use variables that are no t Instance Variables, Class Variables, o r Metho d Parameters.
Instead we'll use Lo cal Variable s. Lo cal variables are variables that are o nly kno wn within the sco pe o f their
blo ck o f co de . In this case, within the bo dy o f a metho d.
Here's an illustratio n o f what we're do ing:

Because the bo tto m o f the triangle is ho rizo ntal, the bo tto mY co o rdinate is used twice.
Once we have the fo rmal parameters passed to the metho d drawT riangle ( ), we can use them to make three
new lo cal variables:
int rightX = bo tto mX + base;
int to pX = bo tto mX + base/2;
int to pY = bo tto mY - height;
Then we can use these as co o rdinates fo r three po ints:
<to pX, to pY> , <bo tto mX, bo tto mY>, and <rightX, bo tto mY>

No w it'll be easier to decipher the parameters we send in the three drawLine ( ) calls (as sho wn in the
diagram abo ve).
Make a new pro ject fo r Lesso n 11 called java1_Le sso n11, and make a new class called Me t ho dDe m o that
uses the super java.apple t .Apple t . Then, edit Metho dDemo as fo llo ws:
CODE TO TYPE: Metho dDemo .java
import java.awt.*;
import java.applet.Applet;
public class MethodDemo extends Applet {
public void paint(Graphics g) {
drawTriangle(g, 80, 120, 100, 110);
drawTriangle(g, 125, 140, 60, 70);
}
private
t height) {
int
int
int

void drawTriangle(Graphics g, int bottomX, int bottomY, int base, in


rightX = bottomX + base;
topX = bottomX + base/2;
topY = bottomY - height;

//easier to read drawLine calls


g.drawLine(bottomX, bottomY, rightX, bottomY);
g.drawLine(rightX, bottomY, topX, topY);
g.drawLine(topX, topY, bottomX, bottomY);
}
}
Run it. It sho uld lo o k familiar.
Two impo rtant things yo u sho uld kno w abo ut lo cal variables:
Lo cal variables do not get default values. Yo u must give them initial values.
Lo cal variables o nly exist within their blo ck o f co de. The same is true o f metho d parameters. That
is, the sco pe o f lo cal variables and metho d parameters is so lely within the bo dy o f the metho d in
which they are defined.
In yo ur new Me t ho dDe m o Class, edit the Lo cal Variables as fo llo ws:
CODE TO EDIT: Metho dDemo .java
import java.awt.*;
import java.applet.Applet;
public class MethodDemo extends Applet {
public void paint(Graphics g) {
drawTriangle(g, 80, 120, 100, 110);
drawTriangle(g, 125, 140, 60, 70);
}
private void
t height) {
rightX =
int topX
int topY

drawTriangle(Graphics g, int bottomX, int bottomY, int base, in


bottomX + base;
= bottomX + base/2;
= bottomY - height;

//easier to read drawLine calls


g.drawLine(bottomX, bottomY, rightX, bottomY);
g.drawLine(rightX, bottomY, topX, topY);
g.drawLine(topX, topY, bottomX, bottomY);
}
}
Yo u sho uld see this erro r: right X canno t be re so lve d. The erro r o ccurs because we haven't declared the
variable t ype .

No w edit the co de as fo llo ws and see what happens:


CODE TO EDIT: Metho dDemo .java
import java.awt.*;
import java.applet.Applet;
public class MethodDemo extends Applet {
public void paint(Graphics g) {
drawTriangle(g, 80, 120, 100, 110);
drawTriangle(g, 125, 140, 60, 70);
}
private
t height) {
int
int
int

void drawTriangle(Graphics g, int bottomX, int bottomY, int base, in


rightX;
topX = bottomX + base/2;
topY = bottomY - height;

//easier to read drawLine calls


g.drawLine(bottomX, bottomY, rightX, bottomY);
g.drawLine(rightX, bottomY, topX, topY);
g.drawLine(topX, topY, bottomX, bottomY);
}
}
No t surprisingly, because we just said that lo cal variables do not get default values, we get the erro r: T he
lo cal variable right X m ay no t have be e n init ialize d
Edit the co de again so it lo o ks like this:
CODE TO EDIT: Metho dDemo .java
import java.awt.*;
import java.applet.Applet;
public class MethodDemo extends Applet {
public void paint(Graphics g) {
rightX = 42;
drawTriangle(g, 80, 120, 100, 110);
drawTriangle(g, 125, 140, 60, 70);
}
private
t height) {
int
int
int

void drawTriangle(Graphics g, int bottomX, int bottomY, int base, in


rightX = bottomX + base;
topX = bottomX + base/2;
topY = bottomY - height;

//easier to read drawLine calls


g.drawLine(bottomX, bottomY, rightX, bottomY);
g.drawLine(rightX, bottomY, topX, topY);
g.drawLine(topX, topY, bottomX, bottomY);
}
}
This time yo u get the message: right X canno t be re so lve d, because it's o utside o f the sco pe o f the
metho d in which it was declared. Okay, but it's no t initialized there. Go ahead and initialize it:

CODE TO EDIT: Metho dDemo .java


import java.awt.*;
import java.applet.Applet;
public class MethodDemo extends Applet {
public void paint(Graphics g) {
int rightX = 42;
drawTriangle(g, 80, 120, 100, 110);
drawTriangle(g, 125, 140, 60, 70);
}
private
t height) {
int
int
int

void drawTriangle(Graphics g, int bottomX, int bottomY, int base, in


rightX = bottomX + base;
topX = bottomX + base/2;
topY = bottomY - height;

//easier to read drawLine calls


g.drawLine(bottomX, bottomY, rightX, bottomY);
g.drawLine(rightX, bottomY, topX, topY);
g.drawLine(topX, topY, bottomX, bottomY);
}
}
Co o l, all the erro rs go away. But, since bo th right X o ccurrences are individually declared in each metho d,
they have dif f e re nt value s!
To pro ve this, edit it as fo llo ws:
CODE TO EDIT: Metho dDemo .java
import java.awt.*;
import java.applet.Applet;
public class MethodDemo extends Applet {
public void paint(Graphics g) {
int rightX = 42;
g.drawString("rightX before the method call is " + rightX, 5,170);
drawTriangle(g, 80, 120, 100, 110);
drawTriangle(g, 125, 140, 60, 70);
g.drawString("rightX after the method call is " + rightX, 5,200);
}
private void drawTriangle(Graphics g, int bottomX, int bottomY, int base, in
t height) {
int rightX = bottomX + base;
g.drawString("rightX in the method is " + rightX, 5,185);
int topX = bottomX + base/2;
int topY = bottomY - height;
//easier to read drawLine calls
g.drawLine(bottomX, bottomY, rightX, bottomY);
g.drawLine(rightX, bottomY, topX, topY);
g.drawLine(topX, topY, bottomX, bottomY);
}
}
Run it.
And that's why they're called lo cal! Here's a diagram that sho ws ho w sco pe wo rks:

Metho ds can have their o wn lo cal variables. In the diagram abo ve, the Class variable Cvariable can be
accessed by Me t ho d A and Me t ho d B. Ho wever, the metho d variable m yVar1 is o nly accessible in
Me t ho d A, while m yVar2 is o nly accessible in Me t ho d B.

Note

Fo r better readability and class design, limit the sco pe o f yo ur variables, and keep them as small
as po ssible.

Of co urse lo cal variables are no t o nly fo r enhanced readability; so metimes they're used fo r co mputatio ns o f
metho ds. If lo cal variables are o nly needed fo r a given metho d, then they sho uld o nly be present while that
metho d is being called.

WARNING

Lo cal variables are re -init ialize d each time the metho d is called. Their previo us value
will no t be present when the metho d is called again.

Results and Return


In the previo us lesso n, we mentio ned that the o nly required elements o f a metho d declaratio n are the
metho d's return type, name, a pair o f parentheses, (), and a bo dy between braces, {}. So far we have co vered
everything except the re t urn type.
To get results fro m a metho d (so me call these queries as o ppo sed to commands), we need to use the
reserved wo rd re t urn.
Metho ds that return info rmatio n have two impo rtant traits:
The return t ype must be specified in the metho d declaratio n.
The metho d must use the reserved wo rd re t urn fo llo wed by an expressio n that matches the
specified return type.
Let's start a new class called Re t urnDe m o that extends Applet. T ype into ReturnDemo as sho wn by the
co de in blue belo w:

CODE TO TYPE: ReturnDemo .java


import java.awt.*;
import java.applet.Applet;
public class ReturnDemo extends Applet {
public void paint(Graphics g) {
int answer = areaRectangle(30,40);
g.drawString("area of rectangle is " +answer, 20, 20);
}
private int areaRectangle(int side1, int side2) {
int area = side1 * side2;
return area;
}
}
Run it.
No tice that when a call to a metho d re t urns so mething, yo u can't just call the metho d with
are aRe ct angle (30 ,4 0 );
Because we asked it to return so mething, we need a place in memo ry to put the answer that it returns.
Actually, we could make that call witho ut cho o sing a destinatio n fo r o ur result, and we wo uldn't get any erro rs,
but it wo uld pretty much be like do ing no thing at all. Java will execute the metho d, but then since it has no
place to put the returned result, Java will go o n its merry way as if the metho d never existed.

Let's trace the co de.


In the paint ( ), areaRectangle(30,40); is a call to a metho d which has a return type o f int . So we must
declare a variable to put the returned value into and declare it to be o f the same type that the metho d returns
(in this case int ). We did that with int answer = areaRectangle(30,40);
Likewise, since are aRe ct angle () has an int return type, the variable are a in the line re t urn are a; must be
o f type int . (That's why we have int area = side1 * side2;).
Edit the Re t urnDe m o .java class as sho wn:

CODE TO EDIT: ReturnDemo .java


import java.awt.*;
import java.applet.Applet;
public class ReturnDemo extends Applet {
public void paint(Graphics g) {
int answer = 0;
areaRectangle(30,40);
g.drawString("area of rectangle is " +answer, 20, 20);
}
private int areaRectangle(int side1, int side2) {
int area = side1 * side2;
return area;
}
}
Run it. Of co urse! We to ld the co mputer that the answer was 0 and it stayed that way. This seems pretty
simple, but it's pretty impo rtant to remember: Co m put e rs will do e xact ly what yo u t e ll t he m t o do !
Okay, let's go o ver o ne mo re gro o vy aspect o f co mputer languages. Edit the paint ( ) metho d as sho wn:
CODE TO EDIT: ReturnDemo .java
import java.awt.*;
import java.applet.Applet;
public class ReturnDemo extends Applet {
public void paint(Graphics g) {
g.drawString("area of rectangle is " + areaRectangle(30,40), 20, 20);
}
private int areaRectangle(int side1, int side2) {
int area = side1 * side2;
return area;
}
}
Remember earlier when we said that anywhere yo u can put a value, yo u can put an expressio n? Well, we just
demo nstrated that here. Java will go and do the metho d, and since it's in the St ring parameter fo r the
drawSt ring( ) metho d, it will auto matically cast the returned int value to a St ring, co ncatenate it to the
previo us St ring, "area o f rectangle is," and print the who le St ring with the co ncatenated result.
Go ahead and

Run it.

Building on methods
No w that we have a handy drawT riangle ( ) metho d, let's use it to build a ho use. Open the Me t ho dDe m o
class yo u wo rked o n earlier in this lesso n, and change the paint () metho d and add a drawHo use () metho d
as sho wn in blue (remo ve the co de sho wn in re d):

CODE TO EDIT: Metho dDemo .java


import java.awt.*;
import java.applet.Applet;
public class MethodDemo extends Applet {
public void paint(Graphics g) {
drawHouse(g, 10, 100, 70, 30);
drawHouse(g, 100, 50, 60, 20);
}
private void drawTriangle(Graphics g, int bottomX, int bottomY, int base, in
t height){
int rightX = bottomX + base;
g.drawString("rightX in the method is " + rightX, 5,185);
int topX = bottomX + base/2;
int topY = bottomY - height;
g.drawLine(bottomX, bottomY, rightX, bottomY);
g.drawLine(rightX, bottomY, topX, topY);
g.drawLine(topX, topY, bottomX, bottomY);
}
private
height){
int
int
int
int

void drawHouse(Graphics g, int bottomX, int bottomY, int width, int


rightX = bottomX + width;
topX = bottomX + width/2;
topY = bottomY - height;
halfHeight = height/2;

g.drawRect(bottomX, topY, width, height);


this.drawTriangle(g, bottomX, topY, width, halfHeight);
}
}
Run it. Hey, they kind o f lo o k like envelo pes, to o . So go ahead and think o f them as ho uses o r
envelo pes.
After a metho d is finished, co ntro l returns to the metho d fro m which it was initially invo ked. Let's t race this
pro gram so we can see that mo re clearly.

OBSERVE: Metho dDemo .java


import java.awt.*;
import java.applet.Applet;
public class MethodDemo extends Applet {
public void 1paint(Graphics g) {
2

drawHouse(g, 10, 100, 70, 30);

9drawHouse(g, 100, 50, 60, 20);

}
private void drawTriangle(Graphics g, int bottomX, int bottomY, int base, in
t height){
7
int rightX = bottomX + base;
int topX = bottomX + base/2;
int topY = bottomY - height;
8g.drawLine(bottomX, bottomY, rightX, bottomY);

g.drawLine(rightX, bottomY, topX, topY);


g.drawLine(topX, topY, bottomX, bottomY);
}
private void 3drawHouse(Graphics g, int bottomX, int bottomY, int width, int
height){
4

int rightX = bottomX + width;


int topX = bottomX + width/2;
int topY = bottomY - height;
int halfHeight = height/2;
5g.drawRect(bottomX, topY, width, height);
6this.drawTriangle(g, bottomX, topY, width, halfHeight);

}
}
Let's check o ut the steps Java takes to execute this pro gram in o rder:
1. The Applet calls its inherited init ( ) and st art ( ), and then it calls paint ( ).
2. In the paint ( ) metho d , drawHo use (g, 10 , 10 0 , 7 0 , 30 ); is called.
3. Java sets the fo rmal parameters to :
1. g = g
2. bo tto mX = 10
3. bo tto mY = 10 0
4. width = 70
5. height = 30

4. Inside o f the drawHo use ( ) metho d, so me lo cal variables are set:


1. int rightX = bo tto mX + width;
2. int to pX = bo tto mX + width/2;
3. int to pY = bo tto mY - height;
4. int halfHeight = height/2;

5. Java sees g.drawRe ct (bo t t o m X, t o pY, widt h, he ight ), so it go es to the package java.awt ,
to the class Graphics, finds the metho d drawRe ct ( ), and uses the actual parameters passed to
run it and draw the rectangle.

run it and draw the rectangle.


6 . Java sees a call to this class's metho d named drawT riangle ( ), so Java go es to its definitio n
and sets its fo rmal parameters.
7. So me lo cal variables, based o n the actual parameters, are defined inside o f drawT riangle ( ):
1. int rightX = bo tto mX + base;
2. int to pX = bo tto mX + base/2;
3. int to pY = bo tto mY - height;

8 . Java enco unters each o f the g.drawLine ( ) metho ds o ne at a time, each time it go es to
java.awt and finds the drawLine ( ) metho d in the Graphics class.
9 . Once Java is do ne with the drawT riangle ( ) metho d, it's do ne with the first drawHo use ( )
metho d, but Java is no t do ne with the paint ( ) metho d. Because Java sees another call to
drawHo use ( ), it perfo rms steps 2 thro ugh 8 abo ve all o ver again, but this time with different
parameters.
We can see no w that the order in which we de f ine o ur metho ds makes no difference. (But the o rder in which
we call them can matter). Java will go where yo u tell it to go within the metho ds.
We've co me a really lo ng way, but let's no t sto p here. Let's add a little mo re and paint the ho uses.

Overloading
How Does Java Find the Right Method?
Edit Me t ho dDe m o to include the blue co de belo w:

CODE TO EDIT: Metho dDemo .java


import java.awt.*;
import java.applet.Applet;
public class MethodDemo extends Applet {
public void start(){
resize(400,200);
// make it bigger so we do not have to expan
d
}
public void paint(Graphics g) {
drawHouse(g, 50, 50, 70, 30);
// for these, added another parameter for house color
drawHouse(g, Color.red, 100, 50, 60, 20);
drawHouse(g, Color.cyan, 150, 100, 160, 50);
}
private
t height){
int
int
int

void drawTriangle(Graphics g, int bottomX, int bottomY, int base, in


rightX = bottomX + base;
topX = bottomX + base/2;
topY = bottomY - height;

g.drawLine(bottomX, bottomY, rightX, bottomY);


g.drawLine(rightX, bottomY, topX, topY);
g.drawLine(topX, topY, bottomX, bottomY);
}
private void drawHouse(Graphics g, int bottomX, int bottomY, int width, int
height){
int
int
int
int

rightX = bottomX + width;


topX = bottomX + width/2;
topY = bottomY - height;
halfHeight = height/2;

g.drawRect(bottomX, topY, width, height);


this.drawTriangle(g, bottomX, topY, width, halfHeight);
}
// provide another drawHouse method that paints if passed a color
private void drawHouse(Graphics g, Color paintMe, int bottomX, int bottomY,
int width, int height){
int topY = bottomY - height;
drawHouse(g, bottomX, bottomY, width, height); //draw the house using th
e original signature of drawHouse.
g.setColor(paintMe);
// set color to that passed
g.fillRect(bottomX, topY, width, height);
}
}
Run it. Ho w abo ut that? We painted the side o f the ho uses. Go o d jo b! (We'll leave it to yo u to fill in the
ro o f! Maybe yo u'll want to o verlo ad drawTriangle?)
What? Two metho d definitio ns with the same name? Yep, but they have different parameters. In fact the
seco nd definitio n has 6 parameters. The seco nd parameter in the seco nd definitio n is a Co lo r. Ho w do es
Java kno w which o ne to use?
Java takes these steps to find a metho d that has been invo ked:
1. Metho ds are invo ked with the do t o perato r, so Java always kno ws what kind o f Object is being
used to execute the metho d.
2. Once Java kno ws the o bject, it kno ws the Class the o bject is an instance o f because every
variable must be declared as a type.
3. Once Java kno ws the Class, it lo o ks thro ugh that Class's metho ds fo r the pro per metho d name.

4. If mo re than o ne metho d has the same name, we have overloading, so Java will check
parameters (number and type) to find the match. The number and type o f parameters determine the
metho d's signat ure .
Overlo aded metho ds are differentiated by the number and type o f the arguments passed to them (their
signature). In a given Class, yo u can't declare mo re than o ne metho d with the same name and the same
number and type o f arguments, because the co mpiler can't tell them apart.

WARNING

The co mpiler do esn't co nsider return type when differentiating metho ds, so yo u can't
declare two metho ds with the same signature, even if they have different return types.

Because the co mpiler do es no t co nsider return type, different so urces have different definitio ns fo r the
signature o f a metho d.
Fo r a language to distinguish between o verlo aded metho d calls (that is, when the class type and metho d
have the same name), it uses the metho d's name and the parameter number and types to prevent ambiguity.

Summary
Method Declarations
One mo re time: The o nly required elements o f a metho d declaratio n are the metho d's return type, name, a
pair o f parentheses, (), and a bo dy between braces, {} .
Metho d declaratio ns have six co mpo nents, in o rder:
1. Mo difiers--such as public o r privat e (permissio ns), and o thers we'll see in the next lesso n.
2. Return type--the data type o f the value returned by the metho d, o r vo id if the metho d do es no t
return a value.
3. Metho d name--similar to variable names, with the added reco mmendatio n that it begin with a
verb since metho ds are actions.
4. The parameter list in parentheses--a co mma-delimited list o f input parameters, preceded by their
data types, and enclo sed by parentheses ().
If there are no parameters, yo u still must use empty parentheses.
5. An exceptio n list--we'll co ver this later.
6 . The metho d bo dy, enclo sed between braces--the metho d's co de, including the declaratio n o f
lo cal variables, go es here.

main: an important method


We mentio ned earlier that Java pro grams that do no t run o n a bro wser re quire a main metho d to get them
started. The main metho d is the to p-level metho d that initiates executio n o f a pro gram that is no t running o n a
web bro wser. It lo o ks like this:
public static void main (String[] args) { }
When we want to start an applicatio n, we need to find the Class that has the main metho d in it (call it
ClassWithMain), and use this co mmand:
java ClassWithMain
Go o d design practice dictates that the main metho d sho uld do no thing but instantiate and start the Classes o f
the applicatio n. Given this, so me pro grammers define a class named Main.java and the o nly Member o f that
class is the main metho d. This makes it easy to kno w ho w to start Classes, because instead o f lo o king at all
o f the Classes to find the main, yo u can simply call
java Main every time.
Finally, no te that if yo u do no t do this, and yo u have yo ur main within a Class called ExampleClass, then the
main co de needs to e xplicit ly instantiate the Class and call a metho d to get it started.
Start a new Class called Exam ple Class. This time it do esn't extend Applet so leave the superclass as
java.lang.Object.

CODE TO TYPE: ExampleClass


public class ExampleClass
{
int testInstanceVariable = 42;
public static void main(String[] args)
{
System.out.println("The value of the instance variable is " + testInstanceV
ariable);
}
}
Lo o ks simple, huh? Altho ugh there are so me erro rs generated in this Class that mentio n static, and indicate
Class Variables o r Metho ds, we'll ho ld o ff o n discussing them in depth until the next lesso n. See yo u there...

Copyright 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Adding Interaction using Components and Listeners


When yo u co mplete this lesso n, yo u will be able to :

Lesson Objectives
add a user interface.
Implement a listener interface.

Revisiting the Dukes Class and Applet


Let's revisit o ur o ld pal Duke (deep do wn yo u kno w yo u lo ve him). Grab the Dukes class and the Dukes Applet we
made earlier.
1. Start a new pro ject called java1_Lesso n12.
2. Go to yo ur java1_Le sso n7 pro ject and copy Duke s.java (right-click and Co py).

T o do

3. Go to yo ur java1_Le sso n12 pro ject and paste Duke s.java into the src f o lde r.
4. No w do the same thing with Duke sApple t .java (copy and paste fro m java1_Lesso n7/src).
5. Open up Duke sApple t .java and Run it.

If yo u mo ve the windo w aro und, Duke can get a little messed up. Try mo ving the Applet o ff o f the screen like this and
see:

No w, mo ve it back o n screen and no tice any change s:

Do it a few mo re times.
The Applet gets messed up when we refresh the screen like that.
The pro blem is that Dukes o nly changes the part o f itself that needs to be repainted (in this case, the part that was
o ffscreen). The call to paint the Applet co mes fro m the Applet itself, no t fro m the user. But Java is a language fo r
building so ftware, and so ftware is fo r humans to use. So let's give the users so mething to click o n that makes Dukes
change upo n user directio n instead.

A User Modification Example


No w let's get the user to interact with o ur Applet. Again, using the po wer o f m o dularit y, we'll leave the Dukes class as
it is, and just present it differently, using a different Applet. The Duke sApple t class will change because that's where
the "presentatio n" o r Graphical User Interface (GUI) is lo cated in Applets. In this example we're go ing to add a GUI
co mpo nent called a "List" and use a "Listener" which is a type o f Interface. We'll refer to the example to explain these
new co ncepts in detail later in the lesso n:
Start a new class called Duke sApple t GUI. Make sure it has the java.applet.Applet Superclass.

CODE TO TYPE IN BLUE: DukesAppletGUI.java


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class DukesAppletGUI extends Applet implements ActionListener{
Dukes myDuke;
String action;

// Instance Variable giving the instance name "myDuke"


// Instance Variable telling what action is being done

public void init()


// init method
{
List actionList = new List(3); // makes a list to choose from
actionList.add("wave");
// give the list 3 choices
actionList.add("think");
actionList.add("write");
actionList.addActionListener(this); // tell Java to listen for user input
add(actionList);
// add the list to the Applet
myDuke =new Dukes();
action = myDuke.getActionImage();

// make an instance of Duke


// see what Duke's current action is

}
public void paint(Graphics g)
// paint method
{
Image myAction = getImage(getDocumentBase(), action);
g.drawString(myDuke.getAction(), 10,165);
g.drawString(myDuke.getMessage(), 10,180);
g.drawImage(myAction, 20, 50, Color.white, this);
}
public void actionPerformed(ActionEvent evt)
{
String userChoice = evt.getActionCommand();
if (userChoice == "write") action = myDuke.write();
else if (userChoice == "think") action = myDuke.think();
else if (userChoice == "wave") action = myDuke.wave();
repaint();

// if a different choice has been made, call our paint through repai

nt()
}
}

Run it. To pick a cho ice in the bo x, do uble-click o n it. Scro ll fo r mo re cho ices.
Befo re we examine this co de in detail, let's discuss int e rf ace s.

Introduction to Interfaces
Interfaces are quite simple to create and use, but they can still be tricky to understand. In this co urse we're just go ing to
learn the basics, but there's mo re to co me o n interfaces later in the Java co urse series. Fo r Java pro grammers, the
wo rd interface can have several meanings. Fo r instance, there is a Graphical User Interface (GUI), which is an interface
between users and a piece o f so ftware. But that's no t the definitio n we're using in this lesso n, even tho ugh we're using
a Listener Interface to make a GUI fo r o ur pro gram. We're using the term Int e rf ace here to mean a t ype , so rt o f like a
Class that defines metho ds, but do esn't implement them. The term int e rf ace is used because this type is analogous
to an actual interface yo u're used to using, but it's mo re like an interface between Java o bjects.
So Java has a t ype called an Int e rf ace that defines metho ds, but do esn't implement them. And when we say doesn't
implement the methods, we mean there are no brackets {} , and so no co de between them to be implemented. So the
metho ds in an interface do n't do anyt hing--ye t . Let's take a lo o k. The Actio nListener interface we're using in this
example lo o ks like this in the API:

Definitio n o f the Actio nListener Interface fro m the API


public interface ActionListener extends java.util.EventListener{
public void actionPerformed(ActionEvent e);
}
We fo und the definitio n in the API entry o n the interface Actio nListener. What else do we kno w abo ut this interface? In
additio n to the definitio n, we kno w that metho ds aren't implemented in an interface.
This particular Actio nListener interface o nly has one metho d, but an interface can have any number o f metho ds. No tice
that the act io nPe rf o rm e d( ) metho d do esn't have a bo dy, so it do esn't do anything. It's set up to receive an o bject o f
type Act io nEve nt , but because its return type is vo id, it isn't suppo sed to return anything. An interface's metho ds are
implemented when we im ple m e nt them, when we define its metho ds. Once we do that, then o ur o bject can claim that
it's the same type o f o bject as the interface.
Why wo uld anyo ne want to define an interface? Why wo uld anyo ne want to define metho ds that aren't implemented?
Well, there are several reaso ns. It simulates multiple inheritance, and aids in po lymo rphism. And o nce we implement
an interface, o ther o bjects kno w f o r sure that we are implementing a set o f metho ds, and we kno w that if we
implement these o bjects, that we can receive all that tho se o bjects have to o ffer us f o r sure . In fact, by rule o f
im ple m e nt at io n we agree as pro grammers to implement all o f the metho ds defined in the interface we are
implementing. This co ncept is best illustrated in the List e ne rs interface.
Yo u can see that in o ur Duke sApple t GUI we've o beyed the rules o f implementatio n by implementing all o f the
metho ds o f Actio nListener:

DukesAppletGUI implements Actio nListeners Metho ds


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class DukesAppletGUI extends Applet implements ActionListener{
Dukes myDuke;
String action;

// Instance Variable giving the instance name "myDuke"


// Instance Variable telling what action is being done

public void init()


// init method
{
List actionList = new List(3); // makes a list to choose from
actionList.add("wave");
// give the list 3 choices
actionList.add("think");
actionList.add("write");
actionList.addActionListener(this); // tell Java to listen for user input
add(actionList);
// add the list to the Applet
myDuke =new Dukes();
action = myDuke.getActionImage();

// make an instance of Duke


// see what Duke's current action is

}
public void paint(Graphics g)
// paint method
{
Image myAction = getImage(getDocumentBase(), action);
g.drawString(myDuke.getAction(), 10,165);
g.drawString(myDuke.getMessage(), 10,180);
g.drawImage(myAction, 20, 50, Color.white, this);
}
public void actionPerformed(ActionEvent evt)
{
String userChoice = evt.getActionCommand();
if (userChoice == "write") action = myDuke.write();
else if (userChoice == "think") action = myDuke.think();
else if (userChoice == "wave") action = myDuke.wave();
repaint();

// if a different choice has been made, call our paint through repai

nt()
}
}
By implementing Act io nList e ne r's metho ds, we've actually given them so mething to do ! Our DukesAppletGUI has
fo llo wed the rules o f implementio n, so no w the Actio nListener interface is no t o nly an Applet, but an Actio nListener as
well. And no w o ur Dukes Applet can receive messages fro m o bjects that send them to Actio nListener, and even o ur
Dukes Applet do es so mething with tho se things.

An Analogy: Antenna as an Interface


Listeners are great examples o f interfaces and also lend themselves to a nice analo gy. I like to think o f an interface as
a type o f antenna. An antenna is really an interface between so mething sending a signal and yo ur radio , which receives
the signal and then do es so mething with it. Taking o ur analo gy a little further, yo ur radio 's amplifier will implement an
antenna in o rder to receive signals. Of co urse, this amplifier will take signals and pro cess them. Well, suppo se each
type o f antenna has different kinds and numbers o f wires, which play the part o f methods in o ur example. So in the
analo gy, the Am plif ie r is a Class, the Ant e nnas are interfaces, and the wire s are m e t ho ds defined in each o f the
interfaces. Oh, and the Radio St at io n is an o bje ct that sends o ut different signals, o r parameters. Check o ut this
illustratio n:

In o ur analo gy, in o rde r t o im ple m e nt o ne o f t he Ant e nna, o ur am plif ie r must co nne ct o r im ple m e nt all
o f t he wire s o f t hat Ant e nna.
To take o ur analo gy further still, if we want to play a radio statio n (a Radio St at io n o bject, if yo u will) o n o ur Amplifier,
then we need to im ple m e nt the Radio Ant e nna interface by implementing all o f its metho ds (wires): purple Wire ( )
and blackWire ( ). The Radio Antenna interface has a blackWire ( ) and a purple Wire ( ), but they do n't actually do
anything until we implement them with o ur Amplifier. Once we do that, we can receive signals fro m the Radio Statio n
o bject.
Let's really get carried away with o ur Antenna analo gy no w and write do wn Java co de that represents this situatio n.
First, let's define the Radio Antenna interface:
The Radio Antenna Interface
public interface RadioAntenna{
public void purpleWire(Signal S);
public void blackWire(Groud G);
}
No w suppo se we have an Amplifier Class that im ple m e nt s this interface and instantiates the Radio Statio n o bject
(which sends stuff to the interface).

Amplifier class instantiating the Radio Antenna


public Class Amplifier extends ElectronicDevice implements RadioAntenna{
RadioStation Jazz = new RadioStation(103.4);
Jazz.addRadioAntenna(this);
public void purpleWire(LeftSignal l){
Code that does something with l
}
public void blackWire(RightSignal r){
Code that does something with r
}
}
No w, the Amplifier Class has pro perly implemented the Radio Antenna interface, and the Radio St at io n is sending
signals. Since we have an Antenna interface, the Radio Statio n o bject has an addRadio Ant e nna( ) metho d. So when
the Radio Statio n sends a signal, Java auto matically calls the registered interface metho ds purple Wire ( ) and
blackWire ( ) as needed. (All o f that happens behind the scenes and we do n't need to wo rry abo ut it.) Tho se metho ds
wo uld be defined in the Radio Statio n Class (remember this is an analo gy).

T he Listener Interfaces
No w let's examine this co de and learn what's happening here. Even tho ugh it lo o ks like we've do ne a lo t, in reality
we've o nly intro duced two new things to this Applet. We've added a List Object which, when clicked, will send
messages to o ur interface. We've also implemented a type o f int e rf ace called a List e ne r. Our particular "Listener"
is Act io nList e ne r (there are o thers). A listener's jo b is to "listen" fo r events that users can perfo rm o n a co mputer
like click, do uble-click, mo ve the mo use, and so o n. By implementing the Actio nListener Interface, we've made o ur
DukesAppletGUI a Listener, and it's listening fo r particular events. Lo o k at the co lo r co ding o f o ur co de belo w so we
can discuss this further:

DukesAppletGUI.java
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class DukesAppletGUI extends Applet implements ActionListener{
Dukes myDuke;
String action;

// Instance Variable giving the instance name "myDuke"


// Instance Variable telling what action is being done

public void init()


// init method
{
List actionList = new List(3); // makes a list to choose from
actionList.add("wave");
// give the list 3 choices
actionList.add("think");
actionList.add("write");
actionList.addActionListener(this); // tell Java to listen for user input
add(actionList);
// add the list to the Applet
myDuke =new Dukes();
action = myDuke.getActionImage();

// make an instance of Duke


// see what Duke's current action is

}
public void paint(Graphics g)
// paint method
{
Image myAction = getImage(getDocumentBase(), action);
g.drawString(myDuke.getAction(), 10,165);
g.drawString(myDuke.getMessage(), 10,180);
g.drawImage(myAction, 20, 50, Color.white, this);
}
public void actionPerformed(ActionEvent evt)
{
String userChoice = evt.getActionCommand();
if (userChoice == "write") action = myDuke.write();
else if (userChoice == "think") action = myDuke.think();
else if (userChoice == "wave") action = myDuke.wave();
repaint(); // if a different choice has been made, call our paint through repain
t()
}
}
This example wo rks just like o ur analo gy! By im ple m e nt ing the Act io nList e ne r interface, we've made it so that
o bjects like butto ns and lists can call o ur act io nPe rf o rm e d(Act io nEve nt e vt ) and pass it a parameter o f type
Act io nEve nt . Then o ur implemented act io nPe rf o rm e d() metho d takes that event and pro cesses it with the co de
we added to o ur Applet. In this case, the Actio nEvent o bject that was passed to us has its o wn metho d called
ge t Act io nCo m m and(), which grabs the item in the List that was clicked. Our co de checks each po ssible
userChoice and calls o ur Dukes o bject with the co rrespo nding metho d [write(), think(), o r wave ()].
Finally, let's talk abo ut the List o bject. Like the o ther Co mpo nents in AWT, such as butto ns and check bo xes, this List
is an Object that we create an instance o f using the ne w call. The List o bject takes a number as a parameter so that it
kno ws ho w many items are in the selectio n list (in this case, 3). We named this instance o f List, act io nList . The List
o bject has its o wn metho ds, o ne o f which is add(). We call add() fro m o ur instance as actionList.add("think"). That
way, we add all o f the cho ices ("think", "wave", and "write") to the List.
Yo u might have wo ndered ho w the List o bject kno ws to call the act io nPe rf o rm e d( ) metho d at all. Well, if yo u lo o k
in the API, the List co mpo nent has a metho d called addAct io nList e ne r(Act io nList e ne r S) which takes an
Actio nListener as its parameter. In this case, t his is DukesAppletGUI. We tell o ur ListObject to add t his by calling
act io nList .addAct io nList e ne r(t his). And o f co urse Duke sApple t GUI is an Actio nListener because it
implemented the Actio nListener interface. The call to addActio nListener( ) tells Java to call all o f the appro priate
metho ds listed in the Actio nListener interface which Java kno ws. As yo u'll see in a later lesso n, these co mpo nents
can add o ther listeners to o , and we can implement o ther interfaces to capture their events.
Finally, we add the instantiated List act io nList to the Applet using the Applet's inherited add( ) metho d, a metho d

specifically for adding components to the Applet.


As the co urse pro gresses, yo u will implement and change many o f these Classes in all kinds o f ways. Fo r no w, the
go al is to understand the basics o f Classes--that they define variables and metho ds, which help to define the Class
itself and its capabilities. In the next lesso n we'll write o ur o wn classes again, but we'll use so me o f the Classes that
Java has written fo r us to make co ding easier. See yo u there! Cheers!

Copyright 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Modularity: Modifiers, Permissions, and Scope


When yo u co mplete this lesso n, yo u will be able to :

Lesson Objectives
enhance the structure o f Classes using Access Mo difiers, and Class Metho ds and Variables.
use Sco pe in yo ur Classes.

Class Specifications
Pro gramming styles and languages may differ, but the basic ideas behind o bject-o riented design remain the same:
m o dularit y
e ncapsulat io n (includes data-abstractio n and info rmatio n hiding)
inhe rit ance
po lym o rphism (o verlo ading, o verriding)
We'll return to o ur belo ved Duke s class to illustrate ho w so me aspects o f o bject-o riented design are used to
implement the Java language. And we'll get to play aro und and learn so me mo re tricks. After all, pro gramming really is
all abo ut the tricks!

Modularity
Alright, let's get started with the Dukes class fro m Lesso n 7. Yo u remember Dukes, right? Ho w co uld yo u fo rget?
So far we've re-designed o ur Dukes co de a co uple o f times to demo nstrate mo dularity:
Our first Duke example (java1_Lesso n3) was all in o ne Applet file. Here's the running Applet.
Later we edited Dukes to separate the Dukes info rmatio n fro m the Applet info rmatio n. The running Applet
didn't lo o k any different, but the co de was cleaner.
Then we edited o ur pro ject again to allo w the user to cho o se what actio n fo r Duke to take. We kept the same
Dukes.java class, but o nly edited the GUI co mpo nent cho ice in the Applet. Here is the running Applet.
One o f the great characteristics o f mo dular co de (with unique Classes) is that it's much easier to edit, mo dify, and
reuse. In this lesso n, we'll change o ur Applet's appearance by editing the Applet Class. Then we'll add aspects to o ur
Dukes by editing the Dukes Class.
First, let's add to o ur bucket o f tricks. We'll edit the Applet to make a dro p-do wn m e nu list to use instead o f the
scro llable list we did earlier. The easiest way to make these changes will be to edit stuff we already have. Let's grab a
co py o f the Duke sApple t GUI.java file we made in the last lesso n, and also reuse the Duke s.java we've been using
all alo ng.
Once again, make a ne w pro je ct f o r Le sso n 13 and call it java1_Le sso n13. Once yo u've do ne that, let's co py
so me files we've already made.

To
do

1. Copy and Paste Duke s.java fro m the java1_Lesso n7 pro ject to the java1_Lesso n13 pro ject.
2. Copy and Paste Duke sApple t GUI.java fro m the java1_Lesso n12 pro ject to the
java1_Lesso n13 pro ject.

No w let's edit DukesAppletGUI.java:

CODE TO EDIT IN BLUE: DukesAppletGUI.java


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class DukesAppletGUI extends Applet implements ItemListener{
Dukes myDuke;
String action;
public void init() {
Choice actionList = new Choice();
actionList.add("wave");
actionList.add("think");
actionList.add("write");
actionList.addItemListener(this);
add(actionList);
myDuke =new Dukes();
action = myDuke.getActionImage();
}
public void paint(Graphics g)
// paint method
{
Image myAction = getImage(getDocumentBase(), action);
g.drawString(myDuke.getAction(), 10,165);
g.drawString(myDuke.getMessage(), 10,180);
g.drawImage(myAction, 20, 50, Color.white, this);
}
public void itemStateChanged(ItemEvent evt){
int whichOne = ((Choice)evt.getItemSelectable()).getSelectedIndex();
switch (whichOne)
{
case 0: action= myDuke.wave(); break;
case 1: action= myDuke.think(); break;
case 2: action= myDuke.write(); break;
}
repaint();
}
}
No w Run it. No tice that no w we have a dro p-do wn menu o ptio n rather than the scro ll cho ice bo x we had befo re.
The co de in the it e m Se le ct able ( ) metho d implemented the It e m List e ne r interface and made the co de a little
cleaner. But really, there aren't a who le lo t o f changes happening here. Only abo ut 4 lines needed to be edited to
change the GUI co mpo nent into a Cho ice list. Yo u can really see it here---mo dularity and reusable co de mean less
wo rk fo r us!

Modifiers
Access Modifiers--Permissions
Let's add so me capabilities to o ur Duke and give him so me angst. Like the rest o f us, Dukes can get quite
angry having to do all that thinking, writing, and waving co nstantly. Since we are changing a characteristic o f
Dukes, the Class that is changed is, o f co urse, Dukes.
We're go ing to have o ur Duke get angry in three ways: rando m ly, via the Apple t s Co nst ruct o r, o r by use r
int e ract io n. Lo ts o f things can make Duke angry, it seems!
If yo u want to allo w characteristics o f an instance to be specified at the time o f instantiatio n, yo u sho uld
pro vide co de in that class fo r a Co nst ruct o r o f the class, with pro per parameters that specify desired values
fo r the variables.

Edit the Dukes.java file as we have belo w:

CODE TO EDIT: Dukes.java


import java.awt.Color;
public class Dukes {
private Color noseColor = Color.red; // default Dukes have red noses
private boolean angry = false; // default Dukes aren't disgruntled
private String action = "../../images/duke/dukeWave.gif";
private String whatDoing = "Give me something to do";
private String message= "";
private String angryMessage= "";
public Dukes() {
// give Duke instance random values for traits
int rint = (int)(Math.random() * 3); // randomly generates a 0, 1, or 2
if (rint == 0)
{
noseColor = Color.blue;
// more often red by default
action = "../../images/duke/dukeWave2.gif";
message = "What's up with the blue nose!";
}
// randomly decide if Duke is angry
rint = (int)(Math.random() * 3);
if (rint == 1)
{
angry = true;
angryMessage = "I QUIT!!";
Dukes myDuke = new Dukes(noseColor, true);
}
}
// Or, when the applet instantiates the Duke, let it say if he is
angry--a new Constructor.
public Dukes(Color nose, boolean isMad) {
// give Duke instance specified values for traits that are passed from the cl
ass that instantiated
noseColor = nose;
angry = isMad;
}
// Add methods to access new variables
public String getAngryMessage()
{
return angryMessage;
}
public void setAngryMessage(String newMessage)
{
angryMessage = newMessage;
}
public boolean isAngry()
{
return angry;
}
public void setMood()
{
// toggle the boolean value. If it was true it becomes false; if false
it becomes true
angry = !angry;
if (angry == true)
angryMessage= "I QUIT!!";

else
angryMessage= "";
}
public String getAction()
{
return whatDoing;
}
public String getActionImage()
{
return action;
}
public Color getNoseColor()
{
return noseColor;
}
public String getMessage()
{
return message;
}
public String write(){
whatDoing = "I am a writing Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/penduke.gif";
message = "";
}
else {
action = "../../images/duke/penduke2.gif";
message = "My nose feels funny";
}
return action;
}
public String think(){
whatDoing = "I am a thinking Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/thinking.gif";
message = "";
}
else
{
action = "../../images/duke/thinking2.gif";
message = "My nose feels funny";
}
return action;
}
public String wave(){
whatDoing = "I am a waving Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/dukeWave.gif";
message = "";
}
else
{
action = "../../images/duke/dukeWave2.gif";
message = "My nose feels funny";
}
return action;

}
}
Go ahead and save this.
Again, no tice that thanks to mo dularity, we o nly wo rry abo ut the specific changes we want to make, and no t
the o ther metho ds.
And no tice we no w have two Co nstructo rs, o ne with no param e t e rs:
public Duke s()
and o ne with t wo param e t e rs:
public Duke s(Co lo r no se , bo o le an isMad)
We use multiple co nstructo rs because so metimes, when yo u instantiate a class, yo u kno w the variables that
yo u want to have set in that instance and so pass them as parameters, and o ther times yo u simply want to
use the defaults, so no parameters need to be passed. In o ur Co nstructo r with no parameters, the Dukes
decides rando mly whether Duke is angry. If he is angry, then it calls the o ther co nstructo r and sets the
parameters fo r us (the seco nd o ne being t rue ). If WE want to DECIDE whether Duke is angry, we instead call
the Co nstructo r with parameters to specify as such (seco nd parameter is t rue o r f alse ).
Duke s m yDuke = ne w Duke s(no se Co lo r, f alse );
We no w are allo wing so meo ne else's applet to determine Dukes actio n and no t necessarily deciding
rando mly. That's pretty co o l.

WARNING

Do no t use return types fo r Co nstructo rs--no t even vo id!


Co nstructo rs always return an instance o f the type o f Object they are co nstructing, so they
do no t need a return type.

Since we are allo wing Duke to have a new characteristic (angry), and he's expressing this characteristic, we
added a variable so we can see what he says:
privat e St ring angryMe ssage = " " ;
No tice in the co de that the inst ance variable s are all privat e because we do n't want them changed directly.
This is an example o f e ncapsulat io n (info rmatio n hiding). (Yo u'll see later why we want to hide variables
fro m o thers and make them accessible thro ugh metho ds o nly.)
We've also added metho ds the user can use to change the characteristics and/o r see what they are (instead
o f accessing them directly).
public St ring ge t AngryMe ssage ()
public vo id se t AngryMe ssage (St ring ne wMe ssage )
public bo o le an isAngry()
public vo id se t Mo o d()

No tice that o ur access and change metho ds are public to allo w o thers to use them to find and set attributes.
Users o f the co de (access fro m o ther classes) canno t see the info rmatio n unless we allo w them to with
public metho ds, and they can o nly change variables by using the metho ds we pro vide.
Let's use this class, and then discuss access permissio ns in depth.
No w let's change the user interface in DukesAppletGUI.java to take advantage o f these new features in
Dukes.java.

CODE TO EDIT: DukesAppletGUI fo r new Variable access and Co nstructo r


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class DukesAppletGUI extends Applet implements ItemListener{
Dukes myDuke;
String action;
public void init() {
Choice actionList = new Choice();
actionList.add("wave");
actionList.add("think");
actionList.add("write");
actionList.addItemListener(this);
add(actionList);
myDuke =new Dukes();
action = myDuke.getActionImage();
Checkbox isAngry = new Checkbox("angry", myDuke.isAngry());
add(isAngry);
isAngry.addItemListener(this);
}
public void paint(Graphics g) {
Image actionChoice = getImage(getDocumentBase(), action);
g.drawString(myDuke.getAction(), 10,165);
g.drawString(myDuke.getMessage(), 10,180);
g.drawImage(actionChoice, 20, 50, Color.white, this);
g.drawString(myDuke.getAngryMessage(), 110,110);
}
public void itemStateChanged(ItemEvent evt){
if (evt.getItem().toString() == "angry")
myDuke.setMood();
else
{
int which = ((Choice)evt.getItemSelectable()).getSelectedIndex();
switch (which)
{
case 0: action= myDuke.wave(); break;
case 1: action= myDuke.think(); break;
case 2: action= myDuke.write(); break;
}
}
// make sure you see the curly bracket here too!
repaint();
}
}

And Run it.


We've added a Che ckbo x to allo w us (the user) to decide whether the Duke is angry, and if he is, we let him
send a clear message.
Mo dularity is used in this class (DukeAppletGUI) and the Dukes class, and bo th co ntain the variable name
"isAngry". Fo r the Applet, it's the name o f a Checkbo x instance (in the init() metho d); fo r the Dukes it's a
metho d to see if Duke IS angry. As lo ng is there is an instance name in fro nt o f the do t (e.g.,
myDuke.isAngry()), Java kno ws exactly where to get the right use o f "isAngry". If there is no t a do t with an
instance name in fro nt o f it, Java kno ws to lo o k in the class itself (i.e., the co de that uses it).

This is a nice feature o f o bject-o riented pro gramming languages--yo u never have to wo rry abo ut variables
that so meo ne else used, because the co mpiler will kno w which variable sho uld be used by its presence in a
certain class.

What Permissions Allow


Classes, instance and class variables, and instance and class metho ds can all have acce ss m o dif ie rs.
Two co mmo nly used permissio ns that pro mo te encapsulatio n o f class info rmatio n are:
public
privat e
We have already seen that variables defined in a metho d are local to the metho d and are no t kno wn o utside
o f the metho d (by variable sco pe ). Metho d variables are implicitly private to the metho d in which they are
defined. In this sectio n, we are no t lo o king at the metho d variables, but access to the metho d itself.
First, within a Class, any instance o r class variables o f a class are accessible by any metho d o f that class
since they are defined at the same level o r "abo ve" the metho ds themselves.
Mo difiers fo r permissio ns indicate who o ut side t he class may access things. Fo r example, the private
variables (and metho ds) can o nly be seen (o r accessed) by o ther metho ds o f that same class; that's why we
call them private. Privat e variables require public "get" and "put" metho ds fo r "o utside" access and changes.
Public means accessible by any class.
T he Ps f o r Pe rm issio ns: public, privat e , pro t e ct e d, package
public--any and all classes can access (as lo ng as its package is visible (impo rted)).
public vo id AnyOneCanAccess() {}
privat e --accessible o nly to tho se within the class they are defined. They are no t available to
subclasses.
privat e String CreditCardNumber;
pro t e ct e d--all classes in package and subclasses o f the class inside and o utside package.
pro t e ct e d String FamilySecrets;
"friendly"--no specific declaratio n, the default, also kno wn as "package" because it allo ws access
to any o bjects inside the same package. ("Package" will be co vered in detail in a later co urse in this
series.)
vo id MyPackageMetho d() {}

Mo difier

Visibility

public

All classes where package is visible

privat e

No ne (o nly within o wn class)

pro t e ct e d

Classes in package and subclasses inside o r o utside package

no ne (default) Classes in same package

1. Open the DukesAppletGUI.java file in the Edito r.

T o do

2. Lo o k in the init () metho d, at the line:


Che ckbo x isAngry = ne w Che ckbo x(" angry" , m yDuke .isAngry());

Within that line is a call to the "get" metho d o f the Duke s Class's isAngry() metho d thro ugh
m yDuke .isAngry().

T ip

As a naming co nventio n, names o f metho ds that return bo o leans (t rue o r f alse ) start with is in
fro nt o f the variable name. Accesso r metho ds use ge t as seen in isAngry()). Getter metho ds
ge t values and start with ge t , setter metho ds se t values and start with se t .

Try to ge t the value o f the instance variable angry wit ho ut go ing thro ugh the accesso r metho d: i.e., using:
m yDuke .angry:

CODE TO EDIT IN BLUE:DukesAppletGUI.java


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class DukesAppletGUI extends Applet implements ItemListener{
Dukes myDuke;
String action;
public void init() {
Choice actionList = new Choice();
actionList.add("wave");
actionList.add("think");
actionList.add("write");
actionList.addItemListener(this);
add(actionList);
myDuke =new Dukes();
action = myDuke.getActionImage();
Checkbox isAngry = new Checkbox("angry", myDuke.angry);
add(isAngry);
isAngry.addItemListener(this);
}
public void paint(Graphics g)
// paint method
{
Image myAction = getImage(getDocumentBase(), action);
g.drawString(myDuke.getAction(), 10,165);
g.drawString(myDuke.getMessage(), 10,180);
g.drawImage(myAction, 20, 50, Color.white, this);
}
public void itemStateChanged(ItemEvent evt){
int whichOne = ((Choice)evt.getItemSelectable()).getSelectedIndex();
switch (whichOne)
{
case 0: action= myDuke.wave(); break;
case 1: action= myDuke.think(); break;
case 2: action= myDuke.write(); break;
}
repaint();
}
}

No w t ry to run this.
Yo u sho uld see this erro r:
T he f ie ld Duke s.angry is no t visible
Since yo u are "in" the DukesAppletGUI class and no t the Dukes class, yo u can't see Dukes' private variables
o r metho ds.
We could make the angry variable in the Dukes class public to fix the erro r:

1. Open the Dukes.java class.

T o do

2. Change
privat e bo o le an angry = f alse ;
to
public bo o le an angry = f alse ;.
3. Save it.
4. Go back to the DukeAppletGUI class that had the erro rs.

All the erro rs are go ne no w because the variable is public (it's no t illegal to expo se o ur private parts in Java,
but it is rude--and it vio lates o ur data-hiding co nventio n, to o . Let's see if it mattered here (it can so metimes,
as we'll see later in this lesso n):

T o do

1. Save bo th classes and Run the applet.


2. Click the angry Checkbo x o ver and o ver.

Whew, everything still wo rks fine in this example, but there are cases where it co uld result in dat a
co rrupt io n. (We'll co ver that in a later co urse in this series as well.)
Encapsulatio n and data-hiding prevent data co rruptio n because they prevent users fro m changing o ne aspect
o f co de witho ut co nsidering the co nsequences that change may have o n o ther aspects.
So me o f the great advantages o f mo dularity and encapsulatio n are:
Yo ur co de is safer fro m user co rruptio n, because even when yo ur classes allo w changes, yo u get
to determine what users can and canno t access.
If yo ur co de has an erro r in it, yo u can easily trace it back to yo ur encapsulated chunk o f co de. This
way yo u o nly have to change it o nce--no t thro ugho ut yo ur pro gram.

Be sure and put the Dukes.java and DukesAppletGUI.java back into their o rginal fo rm by making the angry
variable privat e in Dukes.java, and fixing the line Che ckbo x isAngry = ne w Che ckbo x(" angry" ,
m yDuke .isAngry()); in DukesAppletGUI.java.
Keep go ing, yo u're do ing great!
Copyright 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Class Members, Constants and main


When yo u co mplete this lesso n, yo u will be able to :

Lesson Objectives
use Class members with static mo difier.
use the m ain metho d.
use the f inal mo difier.

Static Members
In previo us lesso ns we used metho ds that use static variables such as Co lo r.re d. Also called Class Variable s (as
o ppo sed to Instance Variables), st at ic variables do n't change. We also used static Class Me t ho ds when we used
metho ds like Mat h.rando m ().
Let's take a lo o k at these in the API
. Click o n the API link pro vided in Eclipse, find the java.lang package , and scro ll
do wn to the Mat h class . No tice that the mo difiers in the left co lumn all say static .
No w go back to the java.lang package. Get the Int e ge r class.
No tice that mo st o f the Fields and Metho ds in that Class also have the mo difier static.
Recall that a Class can co ntain o nly:
Fie lds
Me t ho ds
But Fields and Metho ds will be either:
Inst ance members o r
Class (keywo rd st at ic) members
Me m be rs o f a class (Fields and Metho ds) are generally o nly accessible o nce yo u have instantiated the class to make
an inst ance . Once yo u have the instance, yo u can use the do t o perato r to get the values o f the fields, o r to invo ke the
metho ds.
Me m be rs that have the st at ic mo difier are Class variable s o r m e t ho ds, so they're accessible e it he r thro ugh the
do t o perato r o r thro ugh their Class nam e . As such, it isn't necessary to create an instance to use a Class Variable o r
Class Metho d. Class variable s and m e t ho ds o ften belo ng to Classes that are co mmo nly used fo r auxiliary
purpo ses in yo ur Classes (fo r example, java.lang.Mat h).
Okay, let's get crackin' and put o ur new kno wledge to wo rk. Create a new pro ject fo r this lesso n called
java1_Le sso n14 , and co py and paste Duke s.java and Duke sApple t GUI.java fro m the java1_Lesso n13 pro ject to
java1_Lesso n14 pro ject.
We're go ing to change an instance reference to a class reference and no tice that Eclipse will yell at us, and make so me
suggestio ns fo r fixing it.
Ope n Duke s.java and lo o k f o r Class re f e re nce s:

OBSERVE: In Dukes.java, no tice the use o f Class variables and metho ds.
import java.awt.Color;
public class Dukes {
private Color noseColor = Color.red; // default Duke's have red noses
private boolean angry = false; // default Duke's aren't usually disgruntled
private String action = "../../images/duke/dukeWave.gif";
private String whatDoing = "Give me something to do";
private String message= "";
private String angryMessage= "";
public Dukes() {
// give Duke instance random values for traits
int rint = (int)(Math.random() * 3); // randomly generates a 0, 1, or 2
if (rint == 0)
{
noseColor = Color.blue;
// more often red by default
action = "../../images/duke/dukeWave2.gif";
message = "What's up with the blue nose!";
}
// randomly decide if Duke is angry
rint = (int)(Math.random() * 3);
if (rint == 1)
{
angry = true;
angryMessage = "I QUIT!!";
Dukes myDuke = new Dukes(noseColor, true);
}
}
// Or, when the applet instantiates the Duke, let it say if he is angrya new Constructor.
public Dukes(Color nose, boolean isMad) {
// give Duke instance specified values for traits which are passed from the class th
at instantiated
noseColor = nose;
angry = isMad;
}
// Add methods to access new variables
public String getAngryMessage()
{
return angryMessage;
}
public void setAngryMessage(String newMessage)
{
angryMessage = newMessage;
}
public boolean isAngry()
{
return angry;
}
public void setMood()
{
// toggle the boolean value. If it was true it becomes false; if false it beco
mes true
angry = !angry;
if (angry == true)
angryMessage= "I QUIT!!";

else
angryMessage= "";
}
public String getAction()
{
return whatDoing;
}
public String getActionImage()
{
return action;
}
public Color getNoseColor()
{
return noseColor;
}
public String getMessage()
{
return message;
}
public String write(){
whatDoing = "I am a writing Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/penduke.gif";
message = "";
}
else {
action = "../../images/duke/penduke2.gif";
message = "My nose feels funny";
}
return action;
}
public String think(){
whatDoing = "I am a thinking Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/thinking.gif";
message = "";
}
else
{
action = "../../images/duke/thinking2.gif";
message = "My nose feels funny";
}
return action;
}
public String wave(){
whatDoing = "I am a waving Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/dukeWave.gif";
message = "";
}
else
{
action = "../../images/duke/dukeWave2.gif";
message = "My nose feels funny";
}
return action;

}
}

Acco rding to co nventio n, Classes start with capital letters and Instances start with lo wer-case letters. This
allo ws us to identify whether metho ds and variables are Class members (static).

T ip

No w, let's experiment o n DukesAppletGUI.java. Try using the Class name instead o f the instance name (Dukes
instead o f myDuke) in a metho d call:
CODE TO TYPE: In the co de belo w, change myDuke to Dukes.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class DukesAppletGUI extends Applet implements ItemListener{
Dukes myDuke;
String action;
public void init() {
Choice actionList = new Choice();
actionList.add("wave");
actionList.add("think");
actionList.add("write");
actionList.addItemListener(this);
add(actionList);
myDuke =new Dukes();
action = myDuke.getActionImage();
Checkbox isAngry = new Checkbox("angry", myDuke.isAngry());
add(isAngry);
isAngry.addItemListener(this);
}
public void paint(Graphics g) {
Image actionChoice = getImage(getDocumentBase(), action);
g.drawString(Dukes.getAction(), 10,165);
g.drawString(myDuke.getMessage(), 10,180);
g.drawImage(actionChoice, 20, 50, Color.white, this);
g.drawString(myDuke.getAngryMessage(), 110,110);
}
public void itemStateChanged(ItemEvent evt){
if (evt.getItem().toString() == "angry")
myDuke.setMood();
else
{
int which = ((Choice)evt.getItemSelectable()).getSelectedIndex();
switch (which)
{
case 0: action= myDuke.wave(); break;
case 1: action= myDuke.think(); break;
case 2: action= myDuke.write(); break;
}
}
// make sure you see the curly bracket here too!
repaint();
}
}

Yo u'll get this erro r:


Canno t m ake st at ic re f e re nce t o no n-st at ic m e t ho d ge t Act io n() f ro m t ype Duke s
The pro blem here is that we've made a reference to a Class member that hasn't been declared static. Alright then, let's
fo llo w Eclipse's advice and make the getActio n() metho d static just to see what happens. In fact, let Eclipse do it fo r
yo u:

Or yo u can go to Dukes.java and add the st at ic mo difier to the getActio n() metho d yo urself:

CODE TO TYPE: Make getActio n() static in Dukes.java.


import java.awt.Color;
public class Dukes {
private Color noseColor = Color.red; // default Duke's have red noses
private boolean angry = false; // default Duke's aren't usually disgruntled
private String action = "../../images/duke/dukeWave.gif";
private String whatDoing = "Give me something to do";
private String message= "";
private String angryMessage= "";
public Dukes() {
// give Duke instance random values for traits
int rint = (int)(Math.random() * 3); // randomly generates a 0, 1, or 2
if (rint == 0)
{
noseColor = Color.blue;
// more often red by default
action = "../../images/duke/dukeWave2.gif";
message = "What's up with the blue nose!";
}
// randomly decide if Duke is angry
rint = (int)(Math.random() * 3);
if (rint == 1)
{
angry = true;
angryMessage = "I QUIT!!";
Dukes myDuke = new Dukes(noseColor, true);
}
}
// Or, when the applet instantiates the Duke, let it say if he is angrya new Constructor.
public Dukes(Color nose, boolean isMad) {
// give Duke instance specified values for traits which are passed from the class th
at instantiated
noseColor = nose;
angry = isMad;
}
// Add methods to access new variables
public String getAngryMessage()
{
return angryMessage;
}
public void setAngryMessage(String newMessage)
{
angryMessage = newMessage;
}
public boolean isAngry()
{
return angry;
}
public void setMood()
{
// toggle the boolean value. If it was true it becomes false; if false it beco
mes true
angry = !angry;
if (angry == true)
angryMessage= "I QUIT!!";

else
angryMessage= "";
}
public static String getAction()
{
return whatDoing;
}
public String getActionImage()
{
return action;
}
public Color getNoseColor()
{
return noseColor;
}
public String getMessage()
{
return message;
}
public String write(){
whatDoing = "I am a writing Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/penduke.gif";
message = "";
}
else {
action = "../../images/duke/penduke2.gif";
message = "My nose feels funny";
}
return action;
}
public String think(){
whatDoing = "I am a thinking Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/thinking.gif";
message = "";
}
else
{
action = "../../images/duke/thinking2.gif";
message = "My nose feels funny";
}
return action;
}
public String wave(){
whatDoing = "I am a waving Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/dukeWave.gif";
message = "";
}
else
{
action = "../../images/duke/dukeWave2.gif";
message = "My nose feels funny";
}
return action;

}
}
No w we get a different erro r:
Canno t m ake st at ic re f e re nce t o no n-st at ic f ie ld what Do ing
We are go ing to make what Do ing static to see if the reference to Dukes can then be made. We can do that either by
using the Eclipse trick o r by typing it fo r o urselves:

CODE TO TYPE: In Dukes.java, make whatDo ing static.


import java.awt.Color;
public class Dukes {
private Color noseColor = Color.red; // default Duke's have red noses
private boolean angry = false; // default Duke's aren't usually disgruntled
private String action = "../../images/duke/dukeWave.gif";
private static String whatDoing = "Give me something to do";
private String message= "";
private String angryMessage= "";
public Dukes() {
// give Duke instance random values for traits
int rint = (int)(Math.random() * 3); // randomly generates a 0, 1, or 2
if (rint == 0)
{
noseColor = Color.blue;
// more often red by default
action = "../../images/duke/dukeWave2.gif";
message = "What's up with the blue nose!";
}
// randomly decide if Duke is angry
rint = (int)(Math.random() * 3);
if (rint == 1)
{
angry = true;
angryMessage = "I QUIT!!";
Dukes myDuke = new Dukes(noseColor, true);
}
}
// Or, when the applet instantiates the Duke, let it say if he is angrya new Constructor.
public Dukes(Color nose, boolean isMad) {
// give Duke instance specified values for traits which are passed from the class th
at instantiated
noseColor = nose;
angry = isMad;
}
// Add methods to access new variables
public String getAngryMessage()
{
return angryMessage;
}
public void setAngryMessage(String newMessage)
{
angryMessage = newMessage;
}
public boolean isAngry()
{
return angry;
}
public void setMood()
{
// toggle the boolean value. If it was true it becomes false; if false it beco
mes true
angry = !angry;
if (angry == true)
angryMessage= "I QUIT!!";

else
angryMessage= "";
}
public static String getAction()
{
return whatDoing;
}
public String getActionImage()
{
return action;
}
public Color getNoseColor()
{
return noseColor;
}
public String getMessage()
{
return message;
}
public String write(){
whatDoing = "I am a writing Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/penduke.gif";
message = "";
}
else {
action = "../../images/duke/penduke2.gif";
message = "My nose feels funny";
}
return action;
}
public String think(){
whatDoing = "I am a thinking Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/thinking.gif";
message = "";
}
else
{
action = "../../images/duke/thinking2.gif";
message = "My nose feels funny";
}
return action;
}
public String wave(){
whatDoing = "I am a waving Duke";
if (noseColor == Color.red)
{
action = "../../images/duke/dukeWave.gif";
message = "";
}
else
{
action = "../../images/duke/dukeWave2.gif";
message = "My nose feels funny";
}
return action;

}
}
No w go back to Duke sApple t GUI.java and run it.

T ip

Eclipse uses italics to let yo u kno w when a metho d o r field is static, like in "Co lo r.red".

Yo u sho uldn't have any erro rs. Ho we ve r, we have co m ple t e ly change d o ur Class! Eclipse's suggestio ns have
led us astray fro m the o riginal intent o f the Dukes Class. So we can't always take Eclipse's advice. There is a reaso n
that that what Do ing WASN'T static in the first place -- because we wanted what Do ing to be an instance variable i.e.
we wanted it to be different fo r each instance. No w, when we change what Do ing, the change is applied to all
inst ance s o f that Class. So no w all o f instances o f Dukes will be do ing the SAME thing. That's no t what we want. Let's
go ahead and change it back.
1. Change the whatDo ing back to an Instance Variable by remo ving the static keywo rd.

T o do

2. Remo ve the static keywo rd fro m getActio n()


3. Change the Dukes.getActio n() reference in the applet back to myDukes.getActio n()

There, all is well again! The purpo se o f this exercise was to give yo u a feel fo r static variables and references. In the
next sectio n we'll make so me class variables that sho uld be class variables.

Static: Making Your Own


Fo r no rmal, everyday Classes, Java has bo th Class Variables and Instance Variables.
Defining variables within a Class:
If a value changes fo r each instance o f a Class, t he n it sho uld be an instance variable.
If a value remains the same fo r every instance o f a Class, t he n it sho uld be a class variable.
Here are a co uple o f examples to help illustrate this co ncept:
An emplo yee's salary (instance variable), co mpared to the t o pSalary o f all emplo yees (class variable).
A human's co lo rOf Eye s (instance variable), co mpared to the num be rOf Eye s o f all humans (class
variable).
Yo u'll understand the lo gic behind bo th kinds o f variables even better o nce yo u see ho w they're implemented
in Java:
Instance variables each o ccupy their o wn space in memo ry. Changes to a value fo r o ne instance
will have no effect o n o ther instances.
Class variables all o ccupy the same space in memo ry. If the value ever changes, it changes fo r
e ve ry instance in the Class, because they share the same memo ry address lo catio n.
With this in mind, let's think abo ut access. Instances have info rmatio n abo ut the class, but classes do no t
have individual instance access. Instances sho uld be able to access Class info rmatio n, but unless yo u have
the reference o r handle to the instance, yo u canno t access instance info rmatio n.
Let's lo o k at an example o f access to class and instance variables and metho ds:
Make a new Class called Em plo ye e (that do esn't extend Applet).

CODE TO TYPE: Emplo yee.java


class Employee {
private static int topSalary = 195000;
public static void setTopSalary (int s) {
if (s > topSalary)
topSalary = s;
}
}
No tice that we have a class variable (deno ted by static) that is changed thro ugh a class m e t ho d (also
deno ted by static).
No w suppo se ano ther Class wants to create Em plo ye e s. To make testing easier, we'll add a m ain( )
metho d to o ur Emplo yee class. The m ain() metho d is used to create an applicatio n rather than an Applet. In
it, we will invo ke the metho d fro m the Class (Em plo ye e ) as well as invo ke it fro m an instance (e 2). We'll
explain mo re abo ut this later in the lesso n.
Edit the Em plo ye e class as sho wn:
CODE TO TYPE: Add a main metho d to the Emplo yee Class to test static members.
class Employee {
private static int topSalary = 195000;
public static void setTopSalary (int s) {
if (s > topSalary)
topSalary = s;
}
public static void main(String[] args){
Employee e1, e2;
e1 = new Employee();
e2 = new Employee();
Employee.setTopSalary(199000);
// calling by class; can we do this?
e2.setTopSalary(199001);
// calling by instance; can we do this?
}
}
No tice that we get warnings, but no erro rs. Class variables and metho ds can be acce sse d fro m either
individual instances o r the Class. This makes sense; if a member o f the Emplo yee class gets a salary
increase, that Emplo yee's new salary may change the existing to p salary. Or, the to p salary can be changed
by the "bo ss", the Class as a who le.
Ho wever, remember that if the Class variable is changed fo r (o r by) o ne instance, it changes fo r all. Why?
The class variable is lo cated at the same place in the co mputer memo ry fo r everyo ne. Changes made by
o ne affect all.
If a variable is an instance variable, there are co pies in each o bject; if a variable is a class variable, there is
o nly o ne co py, which is shared.

Note

If yo u declare a metho d static, that metho d can o nly access o ther variables o f the Class that are
declared static as well. Class metho ds canno t change instance variables.

Let's add an instance variable and a class metho d to o ur Emplo yee class.

CODE TO TYPE:
class Employee {
private static int topSalary = 195000;
int hoursPerWeek;
public static void setTopSalary (int s) {
if (s > topSalary)
topSalary = s;
// will work (CM, CV)
}
public static void addMoreHours () {
hoursPerWeek++; // won't work (CM, IV)
}
public static void main(String[] args){
Employee e1, e2;
e1 = new Employee();
e2 = new Employee();
Employee.setTopSalary(199000);
// calling by class; can we do this?
e2.setTopSalary(199001);
// calling by instance; can we do this?
}
}
There's that erro r again.
Canno t m ake a st at ic re f e re nce t o t he no n-st at ic f ie ld ho ursPe rWe e k
Okay, no w remo ve the st at ic keywo rd fro m the addMo re Ho urs() metho d, so it lo o ks like this:
public void addMoreHours () {

Java is happy no w.
No w, add two lines o f co de to the main metho d as sho wn belo w:

CODE TO TYPE:
class Employee {
private static int topSalary = 195000;
int hoursPerWeek;
public static void setTopSalary (int s) {
if (s > topSalary)
topSalary = s;
// will work (CM, CV)
}
public static void addMoreHours () {
hoursPerWeek++; // won't work (CM, IV)
}
public static void main(String[] args){
Employee e1, e2;
e1 = new Employee();
e2 = new Employee();
Employee.setTopSalary(199000);
// calling by class; can we do this?
e2.setTopSalary(199001);
// calling by instance; can we do this?
e1.hoursPerWeek = 40;
Employee.hoursPerWeek = 45;
}
Erro r again! Canno t m ake a st at ic re f e re nce t o t he no n-st at ic f ie ld Em plo ye e .ho ursPe rWe e k
Why? Co nsider what the expressio n Em plo ye e .ho ursPe rWe e k is do ing: it's trying to access the no n-static
field o f ho ursPe rWe e k thro ugh the Em plo ye e Class name, a st at ic reference. Instance variables belo ng
to individual instances. Classes canno t access them--it do es no t make sense. Fo r instance, the Class o f
Humans canno t access the instance variable co lo rOf Eye s o f a specific Human, because the class name
"Hum an" do es no t specify which o ne o f its instances it's trying to access.
Co nsider the expressio n e 1.ho ursPe rWe e k: It's trying to access the no n-static (and therefo re instance) field
o f ho ursPe rWe e k, thro ugh the inst ance e 1. There's no pro blem there. A specific emplo yee wo uld wo rk a
specific number o f ho urs in a week.
No w, change the line Em plo ye e .ho ursPe rWe e k = 4 5 ; to e 2.ho ursPe rWe e k = 4 5 ; That sho uld wo rk.

static and main


The example abo ve used so mething new, the m ain( ) metho d.
The m ain( ) metho d is used fo r all Java pro grams that are applicatio ns and no t Applets. Specifically, if yo u
want a pro gram to Run, then yo u need either an applet o r a Class that has a m ain( ) metho d to get the
applicatio n started.
The m ain( ) metho d is always st at ic. That's why Java can get into the Class where the metho d is lo cated to
start the co de befo re yo u ever have an instance o f the class.
Start a new Class called Exam ple Wit hMain (no t an Applet).

CODE TO TYPE: ExampleWithMain


public class ExampleWithMain
{
private int testInstanceVariable = 42;
public static void main(String[] args)
{
System.out.println("The value of the instance variable is " + this.testInst
anceVariable);
}
}
Darn, ano ther erro r! Canno t use t his in a st at ic co nt e xt
Let's remo ve t his fro m the expressio n t his.t e st Inst ance Variable and make it:
Syst e m .o ut .print ln(" T he value o f t he inst ance variable is " + t e st Inst ance Variable );
Grrrr. Ano ther erro r. Canno t m ake a st at ic re f e re nce t o a no n-st at ic f ie ld t e st Inst ance Variable
This erro r o ccurs because m ain( ) is a static metho d, and testInstanceVariable is an instance variable.
These specific pro blems illustrate so me impo rtant stuff abo ut the m ain( ) metho d. Including m ain( ) st at ic,
allo ws Java to get started, but we have no t instantiated the class yet, so we do no t have an instance.
Edit yo ur co de as fo llo ws:
CODE TO TYPE: ExampleWithMain
public class ExampleWithMain
{
private int testInstanceVariable = 42;
public static void main(String[] args)
{
ExampleWithMain myExample = new ExampleWithMain();
System.out.println("The value of the instance variable is " + myExample.
testInstanceVariable);
}
}
The m ain( ) metho d is no t really asso ciated with a f ie ld's access, and it's no t an actio n fo r the class. A
m ain metho d sho uld o nly inst ant iat e and st art the to p-level Class. And, that's go o d pro gramming
practice.

Constructors
Instantiation
We've been using the terms inst ant iat e and init ialize o ften. So what is the difference?
Let's co nsider o ur Dukes example again. Instantiating makes an instance o f the Class. We made Duke s
instances in the DukeAppletGUI when we wro te m yDuke =ne w Duke s();. In the pro cess o f being
inst ant iat e d, o ur m yDuke was init ialize d. Initializing will set all the variables to the values fo r this
instance. This happens inside the Co nstructo r (o r in an Applet, in its init () ) metho d, and also thro ugh
defaults. And instances inherit variables fro m their ancesto rs.
The sequence to allo cate memo ry and to default initialize is:
1. superclass initializatio n
2. instance variable initializatio n
3. co nstructo r initializatio n
The o rder makes sense because the specific subclasses lo wer in a hierarchy o ve rride their parent and thus

their values (2) will "write o ver" the earlier default values set in (1). Then, since the co nstructo r may be passed
specific parameters, they sho uld "write o ver" any defaults that the particular Class initially go t fro m (2).

T ip

When a Class creates an instance o f itself (o r instantiates), it initializes its values.

Constants use the final modifier


Co nstants in a pro gramming language are variables that the pro grammer wants to be accessible to everyo ne
and that remain the same fo r all time. The mo difier keywo rd to make a variable remain the same is f inal .
. Go to the java.lang package. Scro ll again to the Mat h class. No w scro ll do wn to the Fie ld Sum m ary.
Finally, click o n either o f the Fie lds (E o r PI).
Yo u see these mo difiers:
public st at ic f inal do uble E
public st at ic f inal do uble PI
Go o d. We kno w what all o f these mo difiers mean no w, but the co mbinatio n o f these public st at ic f inal
makes PI a do uble variable that is a co nst ant . No tice also , under the descriptio n in the API, it says
Co nst ant Fie ld Value s. Click o n it. It takes yo u to all o f the Field co nstants that Java has defined. Because
co nstants always have the static mo difier, they can be accessed thro ugh the Class name java.lang.Math.PI o r
fo r java.lang classes, simply thro ugh the class and the variable Mat h.PI.

Note

The f inal mo difier indicates that o nce a field receives a value, it can never be changed. Using
co mmo nly accepted naming co nventio ns, fields marked as f inal sho uld be UPPER_CASE with
wo rds separated by the unde rsco re character.

Classe s, m e t ho ds, f ie lds, o r variable s may each have this mo difier and it means essentially the same
thing--that it canno t change--tho ugh it might be said a bit differently:
Mo dif ie r Use d o n Me aning
final

class
metho d
field
variable

Canno t be subclassed
Canno t be o verridden and dynamically lo o ked up
Canno t change its value. static final fields are co mpile-time co nstants.
Canno t change its value.

T emplate and Summary


There are additio nal mo difiers fo r Classes, Metho ds, and Fields, but they are beyo nd the sco pe o f this co urse.
Fo r mo re info rmatio n o n mo difiers, check o ut: Java Mo difiers
The typical o rder fo r mo difiers is (<access> cho ices specified abo ve and the [ ] indicating 0 o r 1 time)
<acce ss> [st at ic] [f inal] ...
P>
Belo w is an example template fo r Class Structure (mo difiers may vary fo r yo ur use):

OBSERVE:
import packageName.ClassName.java
import packageName.*
public class ClassName extends

super

// Instance and Class Variable declarations: Declare and possibly set modifiers a
nd values for variables
private int instanceVariable;
private static int classVariable;
// Define Constructors (if none - looks at supers.

No return type)

public ClassName (formal parameters) {


code
}
// Define methods with no returned values
public void methodName (formal parameters) {
code
}
// Define methods with return values
public returnType methodName (formal parameters) {
code
return ...

// returnType of value returned must match method signature

}
}
Here's o ne mo re link to Java Mo difiers fro m the o nline text o f tuto rialspo int. Mo st o f the less co mmo nly used Java
mo difiers will be explo red in future co urses.
See yo u in the next and final lesso n!
Copyright 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

All Together Now


When yo u co mplete this lesso n, yo u will be able to :

Lesson Objectives
Make ano ther Class and practice making graphical images like circles, hearts, up arro ws, and o ther co o l stuff.
Give the Duke s class the ability to sho w these graphics If the specific instance o f a Duke is "angry".
Add a GUI co mpo nent to o ur Apple t Class so the user can specify whether Duke is in a go o d mo o d o r if we sho uld
sho w him so me lo ve by giving him a Pin.

Interaction and Playing Around


Yo u've do ne a great jo b building so me useful to o ls during the co urse so far; no w let's put them all to gether. Let's give
o ur Duke so me lo ve. It'll make him feel better and it'll give us a chance to practice using classes, o bjects, and
instantiatio n. Later, we'll make real applicatio ns that do mo re useful things, but fo r no w, let's play!

Putting It All T ogether


The Graphics Class allo ws us to draw basic shapes. Let's use these capabilities and make a separate
Class that can draw figures.
Belo w is a class named Mo reImages that adds so me shapes to Java's Graphics Class. We'll use this Class
to allo w o ur Dukes to make vario us graphics.
Let's make a new pro ject fo r lesso n 15 called java1_Le sso n15 , and a new Class called PinIm age s.
After we have PinIm age s bug free, we'll make a simple Applet and demo so me o f the figures in the paint
metho d o f an Applet to see ho w they lo o k. We'll also get to see the po tential o f o ur Butto nImages. Ultimately,
yo u'll cho o se a metho d to make a Butto n, so pay attentio n as yo u type this in and no tice the kinds o f shapes
it allo ws.

CODE TO TYPE: PinImages


// This class will be used by DukesMood which will inherit from Dukes
// It will give a Duke who can make Pins using hearts, crowns, stars, triangles,
etc.
import java.awt.*;
public class PinImages
{
public void drawHeart(Graphics g, Color col, int x, int y, int width){
// I "heart" Duke
g.setColor(col);
g.fillArc(x,y,width/2,width/2,0,180);
g.fillArc(x+ width/2,y,width/2,width/2,0,180);
int [] xTriangle = {x, x+width, x+width/2};
int [] yTriangle = {y+width/4, y+width/4, y+width};
g.fillPolygon(xTriangle, yTriangle, 3);
}
public void fillTriangle(Graphics g, int bottomX, int bottomY, int base, int
height){
// isosceles base at bottom
g.drawLine(bottomX, bottomY, bottomX+base, bottomY);
g.drawLine(bottomX+base, bottomY, bottomX+base/2, bottomY-height);
g.drawLine(bottomX+base/2, bottomY-height, bottomX, bottomY);
int [] xTriangle = {bottomX, bottomX+base, bottomX+base/2};
int [] yTriangle = {bottomY, bottomY, bottomY-height};
g.fillPolygon(xTriangle, yTriangle, 3);
}
public void upArrow(Graphics g, Color col, int x, int y, int arrowbase){
// Duke is movin' on UP
g.setColor(col);
fillTriangle(g, x, y, arrowbase, arrowbase/2);
g.fillRect(x+ 3*arrowbase/8, y, arrowbase/4, arrowbase);
}
}
Save yo ur co de fo r the PinImage Class.
No w we need an Applet so we can lo o k at o ur artwo rk and demo nstrate so me o f the things that the PinImage
class can draw. Make a new class called Im age Make r, so we can see these PinImages displayed.

CODE TO TYPE: Demo


import java.applet.*;
import java.awt.*;
public class ImageMaker extends Applet
{
PinImages demo;
public void init() {
setBackground(Color.black);
demo = new PinImages();
}
public void paint(Graphics g)
{
demo.drawHeart(g, Color.pink, 10,10, 25);
demo.upArrow(g, Color.orange, 10, 70, 30);
// an example Pin using a PinImage shape
g.setColor(Color.red);
g.fillOval(100,100, 80,80);
g.setColor(Color.white);
g.drawString("I",135,120);
demo.drawHeart(g, Color.pink, 125,125, 25);
g.setColor(Color.white);
g.drawString("Duke!",125,170);
}
}
No w Run it.
The first co uple o f expressio ns in the paint ( ) metho d use the instance de m o , but the later o nes use g.
That's because the drawHe art ( ), and upArro w( ) metho ds are defined in the class PinIm age s which has
an instance o f de m o .
The se t Co lo r( ), f illOval( ), and o ther metho ds are defined in the Class Graphics which has an instance o f
g.
So what else is interesting here?
We impo rted java.awt.* so that we co uld see the Graphics class. We do n't need to impo rt anything fo r the
PinImages class because Classes lo cated in the same directo ry are in the same "default" package.

Using Inheritance on our Own


Because we are go ing to add mo re capabilities to o ur Dukes rather than editing to add them into the o ld
Dukes class, let's take advantage o f the co ncept o f inheritance. Dukes that can make Pins will be called
Duke sPins and will be a subclass o f Duke s.
Create ano ther new class in java1_Lesso n15 called Duke sPin.
It will inhe rit fro m Duke s, so let's just co py o ur Dukes class into java1_Lesso n15:
Co py Duke s.java fro m java1_Lesso n14 and paste it into java1_Lesso n15/src.
We'll be adding Dukes, as well as things that relate to sho wing Pins, to o ur new Applet DukesPin. But we're
o nly giving Pins to angry Dukes; after all, they're the o nes who really need lo ve. So , if so meo ne changes
whether Duke is angry, we have to change his ability to get Pins. We'll o ve rride Duke 's se t Mo o d() metho d.
Also no tice ho w o ur Co nstructo r calls supe r(). supe r() is a call to the parent's co nstructo r.
We actually do n't need to do this, because Java calls a parent's co nstructo r by default, but it's here as an
example, in case yo u wanted to use the default co nstructo r and add mo re to it. Anyway, Java will use
Duke sPin's metho ds first, and then will inherit all o f the o ther metho ds and variables fro m the Duke s class.

CODE TO TYPE: Type this into the DukesPin class


import java.awt.Color;
public class DukesPin extends Dukes {
private boolean showingPin;
public DukesPin() {
super();
// you could add more here and Java will do the parent's first and the
n come back for more
}
public DukesPin(Color nose, boolean love) {
super(nose, love);
}
public boolean isShowingPin() {
return showingPin;
}
public void switchShowingPin() {
showingPin =!showingPin;
if (showingPin && !angry)
{
angryMessage= "I don't get a Pin, I'm not angry";
showingPin =!showingPin; // don't let them show Pins since not angry
}
}
public void setMood() {
super.setMood();
// let the parent do the work first, then do what we
need in addition
if (angry == false) showingPin = false;
}
}
Hey, what is go ing o n here? Why all the re d in o ur new class?
All the erro rs are a result o f the access to the variables angry and angryMe ssage . We inherited these
variables fro m Duke s.java. Recall that we gave these variables the privat e permissio ns. And who can see
variables if the access is privat e ? Only the instances o f the Class it se lf . Our new Class inherited fro m
Duke s, so Duke s is its parent/super. Our new Class is no t the same Class as Duke s.
Can yo u fix this?
Since yo u are the autho r o f the co de fo r the Class Duke s, yo u can change the permissio n to pro t e ct e d.
Remember that pro t e ct e d gives access to Classes in the package and subclasse s inside o r o utside the
package (fo r no w, just think o f a package as all the Classes yo u're currently using).

Note

If yo u click o nce o n the red "x", Eclipse will sho w the erro r and suggest ways to fix it.

In the Duke s Class, change the access permissio ns o f these two variables to :
protected boolean angry = false;
and
protected String angryMessage= "";
No w go back to yo ur DukesPin class and all sho uld be well.
That's nice, but if the Class yo u're using is fro m Java's API, yo u can't just go in and change that co de.
But methods are o ften present within Classes in o rder to allo w access to the variables. Do es the Duke s

Class have such metho ds? Why yes, it do es. Let's see if we can fix o ur new Class by using accesso r
metho ds:
Change the permissio ns in the Duke s class back so they are all privat e again. Save it so yo ur erro rs co me
back in Duke sPin.
Lo o k in the Duke s Class and find the accesso rs and mutato rs fo r the needed variables.
Here are the accesso r "get" metho ds (no tice that the mutato r "sets" values):
OBSERVE:
public String getAngryMessage()
{
return angryMessage;
}
public boolean isAngry()
{
return angry;
}
Sweet. Let's use them:
CODE TO TYPE: Type this into the DukesPin class
import java.awt.Color;
public class DukesPin extends Dukes {
private boolean showingPin;
public DukesPin() {
super();
// you could add more here and Java will do the parent's first and the
n come back for more
}
public DukesPin(Color nose, boolean love) {
super(nose, love);
}
public boolean isShowingPin() {
return showingPin;
}
public void switchShowingPin() {
showingPin =!showingPin;
if (showingPin && !isAngry())
{
setAngryMessage("I don't get a Pin, I'm not angry");
showingPin =!showingPin; // don't let them show Pins when not angry
}
}
public void setMood() {
super.setMood();
// let the parent do the work first, then do what we
need in addition
if (isAngry() == false) showingPin = false;
}
}
Excellent! All is well. Let's see what this guy lo o ks like no w.
Make a new Class in the java1_Lesso n15 Pro ject called Duke sPinApple t .

CODE TO TYPE: DukesPinApplet


import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class DukesPinApplet extends Applet implements ItemListener{
DukesPin myDuke;
String action;
Checkbox showPin;
Graphics g;
public void init() {
Choice actionList = new Choice();
actionList.add("wave");
actionList.add("think");
actionList.add("write");
actionList.addItemListener(this);
add(actionList);
myDuke =new DukesPin();
action = myDuke.getActionImage();
Checkbox changeMood = new Checkbox("Angry", myDuke.isAngry());
add(changeMood);
changeMood.addItemListener(this);
showPin = new Checkbox("ShowPin");
add(showPin);
showPin.addItemListener(this);
}
public void paint(Graphics g) {
this.g = g;
Image actionChoice = getImage(getDocumentBase(), action);
g.drawString(myDuke.getAction(), 10,165);
g.drawString(myDuke.getMessage(), 10,180);
g.drawImage(actionChoice, 20, 50, Color.white, this);
g.drawString(myDuke.getAngryMessage(), 110,140);
if (myDuke.isShowingPin())
makePin();
else clearPin();
}
public void itemStateChanged(ItemEvent evt){
if (evt.getItem().toString() == "Angry")
{ myDuke.setMood();
if (!myDuke.isAngry())
showPin.setState(false);
}
else if (evt.getItem().toString() == "ShowPin")
{
myDuke.switchShowingPin();
if (showPin.getState() && !myDuke.isAngry())
showPin.setState(false);
}
else
{
int which = ((Choice)evt.getItemSelectable()).getSelectedIndex();
switch (which)
{
case 0: action= myDuke.wave(); break;
case 1: action= myDuke.think(); break;

case 2: action= myDuke.write(); break;


}
}
repaint();
}
public void makePin()
{
PinImages images =new PinImages();
// make Pin
g.setColor(Color.red);
g.fillOval(120,50, 80,80);
// put something in Pin
g.setColor(Color.white);
g.drawString("I",155,70);
images.drawHeart(g, Color.pink, 145,75, 25);
g.setColor(Color.white);
g.drawString("Duke!",145,120);
}
public void clearPin()
{
g.setColor(Color.white);
g.fillOval(120,50, 80,80);
}
}
Save and Run it.
Click the different checkbo x cho ices to see ho w the GUI reacts.
Go to the API java.awt package. No tice that the Classes Cho ice and Che ckbo x bo th im ple m e nt
It e m Se le ct able . That's why yo u can then implement the It e m List e ne r. Ho wever, since all three o f the
co mpo nents the user can cho o se fro m cause It e m Eve nt s, yo u need to tell Java which actio n to take
depending o n which o f the Che ckbo xes o r Cho ice the user clicked. Yo u do that in the It e m List e ne r's
it e m St at e Change d metho d.
Great jo b! No w that yo u understand the co ncepts behind o bjects, yo u'll really be able to take o ff!
Copyright 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Das könnte Ihnen auch gefallen