Sei sulla pagina 1di 345

:PVS#SBJOPO+BWB‰"-FBSOFST(VJEF Table of Contents (summary)

ND%DITION #OVERS*AVA Intro xxi


1 Breaking the Surface: a quick dip 1
2 A Trip to Objectville: yes, there will be objects 27
3 Know Your Variables: primitives and references 49
-FBSOIPXUISFBET 4 How Objects Behave: object state affects method behavior 71
DBODIBOHFZPVSMJGF )FBE'JSTU 5 Extra-Strength Methods: flow control, operations, and more 95
6 Using the Java Library: so you don’t have to write it all yourself 125
7 Better Living in Objectville: planning for the future 165
8 Serious Polymorphism: exploiting abstract classes and interfaces 197
9 Life and Death of an Object: constructors and memory management 235
.BLF+BWBDPODFQUT 10 Numbers Matter: math, formatting, wrappers, and statics 273
TUJDLUPZPVSCSBJO 11 Risky Behavior: exception handling 315
12 A Very Graphic Story: intro to GUI, event handling, and inner classes 353
+BWB 13
14
15
Work on Your Swing: layout managers and components
Saving Objects: serialization and I/O
Make a Connection: networking sockets and multithreading
399
429
471
16 Data Structures: collections and generics 529
'PPMBSPVOEJO 17 Release Your Code: packaging and deployment 581
UIF+BWB-JCSBSZ 18 Distributed Computing: RMI with a dash of servlets, EJB, and Jini 607
A Appendix A: Final code kitchen 649
B Appendix B: Top Ten Things that didn’t make it into the rest of the book 659
Index 677
"WPJEFNCBSBTTJOH
00NJTUBLFT
Table of Contents (the full version)
Intro
Your brain on Java. (EREYOUARETRYINGTOLEARNSOMETHING WHILEHEREYOURBRAIN
ISDOINGYOUAFAVORBYMAKINGSURETHELEARNINGDOESNTSTICK9OURBRAINSTHINKING h"ETTER
i LEAVEROOMFORMOREIMPORTANTTHINGS LIKEWHICHWILDANIMALSTOAVOIDANDWHETHERNAKED
#FOEZPVSNJOE SNOWBOARDINGISABADIDEAv3OHOWDOYOUTRICKYOURBRAININTOTHINKINGTHATYOURLIFE

BSPVOE DEPENDSONKNOWING*AVA

+BWBQV[[MFT Who is this book for? xxii


What your brain is thinking xxiii

.BLFBUUSBDUJWF Metacognition xxv


Bend your brain into submission xxvii
BOEVTFGVM(6*T
What you need for this book xxviii
Technical editors xxx
Acknowledgements xxxi

ix
,BUIZ4JFSSB#FSU#BUFT
Breaking the Surface Know Your Variables
Java takes you to new places. &ROMITSHUMBLERELEASETOTHEPUBLICASTHE Variables come in two flavors: primitive and reference.
WIMPY VERSION *AVASEDUCEDPROGRAMMERSWITHITSFRIENDLYSYNTAX OBJECT ORIENTED 4HERESGOTTABEMORETOLIFETHANINTEGERS 3TRINGS ANDARRAYS7HATIFYOUHAVEA0ET/WNER
1 FEATURES MEMORYMANAGEMENT ANDBESTOFALLˆTHEPROMISEOFPORTABILITY7ELLTAKEAQUICK
3 OBJECTWITHA$OGINSTANCEVARIABLE/RA#ARWITHAN%NGINE)NTHISCHAPTERWELLUNWRAP
DIPANDWRITESOMECODE COMPILEIT ANDRUNIT7ERETALKINGSYNTAX LOOPS BRANCHING ANDWHAT THEMYSTERIESOF*AVATYPESANDLOOKATWHATYOUCANDECLAREASAVARIABLE WHATYOUCANPUT
MAKES*AVASOCOOL$IVEIN INAVARIABLE ANDWHATYOUCANDOWITHAVARIABLE!NDWELLFINALLYSEEWHATLIFEISTRULYLIKE
ONTHEGARBAGE COLLECTIBLEHEAP
The way Java works 2
Virtual Code structure in Java 7 Declaring a variable (Java cares about type) 50
Machines 24
Anatomy of a class 8 Primitive types (“I’d like a double with extra foam, please”) 51
size
The main() method 9 Java keywords 53
Method Party() Looping 11 int
Reference variables (remote control to an object) 54
0 aload_0
Conditional branching (if tests) 13 ct Object declaration and assignment 55
1 invokespe- Dog obje
cial #1 <Method Coding the “99 bottles of beer” app 14 Objects on the garbage-collectible heap 57
java.lang.Object()>
Phrase-o-matic 16 fido Arrays (a first look) 59
4 return
Fireside chat: compiler vs. JVM 18 Exercises and puzzles 63
You Bet
Compiled Shoot Me

Exercises and puzzles 20 Dog reference


bytecode

How Objects Behave


A Trip to Objectville
State affects behavior, behavior affects state. 7EKNOWTHATOBJECTS
I was told there would be objects. )N#HAPTER WEPUTALLOFOURCODE
HAVESTATEANDBEHAVIOR REPRESENTEDBYINSTANCEVARIABLESANDMETHODS.OWWELLLOOK
INTHEMAIN METHOD4HATSNOTEXACTLYOBJECT ORIENTED3ONOWWEVEGOTTOLEAVETHAT
2 PROCEDURALWORLDBEHINDANDSTARTMAKINGSOMEOBJECTSOFOUROWN7ELLLOOKATWHAT
4 ATHOWSTATEANDBEHAVIORARERELATED!NOBJECTSBEHAVIORUSESANOBJECTSUNIQUESTATE
)NOTHERWORDS METHODSUSEINSTANCEVARIABLEVALUES,IKE hIFDOGWEIGHTISLESSTHAN
MAKESOBJECT ORIENTED// DEVELOPMENTIN*AVASOMUCHFUN7ELLLOOKATTHEDIFFERENCE
POUNDS MAKEYIPPYSOUND ELSEv,ETSGOCHANGESOMESTATE
BETWEENACLASSANDANOBJECT7ELLLOOKATHOWOBJECTSCANIMPROVEYOURLIFE
Methods use object state (bark different) 73
Chair Wars (Brad the OO guy vs. Larry the procedural guy) 28 pass-by-value means Method arguments and return types 74
Inheritance (an introduction) 31
pass-by-copy Pass-by-value (the variable is always copied) 77
Overriding methods (an introduction) 32
Getters and Setters 79
What’s in a class? (methods, instance variables) 34
Encapsulation (do it or risk humiliation) 80
Making your first object 36 copy of
x Using references in an array 83
Using main() 38 1 11
0 11 01
0 00 Exercises and puzzles 88
Guessing Game code 39 00 00
0
Exercises and puzzles 42 X Z
int int
foo.go(x); void go(int z){ }

x xi
Extra-Strength Methods Better Living in Objectville
Let’s put some muscle in our methods. 9OUDABBLEDWITHVARIABLES Plan your programs with the future in mind. 7HATIFYOUCOULDWRITE
PLAYEDWITHAFEWOBJECTS ANDWROTEALITTLECODE"UTYOUNEEDMORETOOLS,IKE CODETHATSOMEONEELSECOULDEXTEND EASILY7HATIFYOUCOULDWRITECODETHATWASFLEXIBLE
5 OPERATORS!NDLOOPS-IGHTBEUSEFULTOGENERATERANDOMNUMBERS!NDTURN
7 FORTHOSEPESKYLAST MINUTESPECCHANGES7HENYOUGETONTHE0OLYMORPHISM0LAN YOULL
A3TRINGINTOANINT YEAH THATWOULDBECOOL!NDWHYDONTWELEARNITALLBYBUILDING LEARNTHESTEPSTOBETTERCLASSDESIGN THETRICKSTOPOLYMORPHISM THEWAYSTOMAKE
SOMETHINGREAL TOSEEWHATITSLIKETOWRITEANDTEST APROGRAMFROMSCRATCH-AYBEA FLEXIBLECODE ANDIFYOUACTNOWˆABONUSLESSONONTHETIPSFOREXPLOITINGINHERITANCE
a build the GAME LIKE3INKA$OT#OMSIMILARTO"ATTLESHIP 
We’re gonnot Com game Understanding inheritance (superclass and subclass relationships) 168
Sink a D Building the Sink a Dot Com game 96 Designing an inheritance tree (the Animal simulation) 170
Starting with the Simple Dot Com game (a simpler version) 98 Avoiding duplicate code (using inheritance) 171
!
Make it Stick
Writing prepcode (pseudocode for the game) 100 Overriding methods 172
"
Test code for Simple Dot Com 102 2OSESARERED
IS-A and HAS-A (bathtub girl) 177
#
VIOLETSAREBL
3QUARE)3 !3 UE
Coding the Simple Dot Com game 103 HAPE THEREV

'OCOM
$ 0ETSCOM ERSEISNTTRUE
 What do you inherit from your superclass? 180
2OSESARERED
Final code for Simple Dot Com 106 VIOLETSAREDE
AR What does inheritance really buy you? 182
% "EER)3 !$RIN
K BUTNOTALL
Generating random numbers with Math.random() 111 DRINKSAREBE
ER Polymorphism (using a supertype reference to a subclass object) 183
& /+ YOURTURN
-
Ready-bake code for getting user input from the command-line 112 WAY NESSOFTH AKEONETHATSHOWSTHE Rules for overriding (don’t touch those arguments and return types!) 190
' !SK-ECOM E) ONE
Looping with for loops 114 BER IF8EX TEN 3 !RELATIONSHIP!NDR
DS9 8)3 !9 EMEM Method overloading (nothing more than method name re-use) 191
       MUSTMAKESE
NSE
Casting primitives from a large size to a smaller size 117 Exercises and puzzles 192
Converting a String to an int with Integer.parseInt() 117
Exercises and puzzles 118

Serious Polymorphism
Using the Java Library Inheritance is just the beginning. 4OEXPLOITPOLYMORPHISM WENEED
Java ships with hundreds of pre-built classes. 9OUDONTHAVETO INTERFACES7ENEEDTOGOBEYONDSIMPLEINHERITANCETOFLEXIBILITYYOUCANGETONLYBY
REINVENTTHEWHEELIFYOUKNOWHOWTOFINDWHATYOUNEEDFROMTHE*AVALIBRARY COMMONLY DESIGNINGANDCODINGTOINTERFACES7HATSANINTERFACE!ABSTRACTCLASS7HATSAN
6 8 ABSTRACTCLASS!CLASSTHATCANTBEINSTANTIATED7HATSTHATGOODFOR2EADTHECHAPTER
KNOWNASTHE*AVA!0)9OUVEGOTBETTERTHINGSTODO)FYOUREGOINGTOWRITECODE YOU
MIGHTASWELLWRITEONLYTHEPARTSTHATARECUSTOMFORYOURAPPLICATION4HECORE*AVALIBRARY
Some classes just should not be instantiated 200
ISAGIANTPILEOFCLASSESJUSTWAITINGFORYOUTOUSELIKEBUILDINGBLOCKS
Object o = al.get(id); Abstract classes (can’t be instantiated) 201
Analying the bug in the Simple Dot Com Game 126 Dog d = (Dog) o; Abstract methods (must be implemented) 203
h'OODTOKNOWTHERESAN!RRAY,ISTIN ArrayList (taking advantage of the Java API) 132 d.bark(); Polymorphism in action 206
THEJAVAUTILPACKAGE"UTBYMYSELF HOW Fixing the DotCom class code 138 Class Object (the ultimate superclass of everything) 208
WOULD)HAVElGUREDTHATOUTv
Building the real game (Sink a Dot Com) 140 Object
Taking objects out of an ArrayList (they come out as type Object) 211
- Julia, 31, hand model
Prepcode for the real game 144 Compiler checks the reference type (before letting you call a method) 213
D og t
Code for the real game 146 o objec
Get in touch with your inner object 214
boolean expressions 151 Polymorphic references 215
Object
cast t
Using the library (Java API) 154 back tohe Object Casting an object reference (moving lower on the inheritance tree) 216
d
Using packages (import statements, fully-qualified names) 155
know is a Dog we
there. Deadly Diamond of Death (multiple inheritance problem) 223
Using the HTML API docs and reference books 158 Dog
Using interfaces (the best solution!) 224
Exercises and puzzles 161 Exercises and puzzles 230

xii xiii
Life and Death of an Object Risky Behavior
Objects are born and objects die. 9OUREINCHARGE9OUDECIDEWHENAND Stuff happens. 4HEFILEISNTTHERE4HESERVERISDOWN.OMATTERHOWGOODA
HOWTOCONSTRUCTTHEM9OUDECIDEWHENTOABANDONTHEM4HE'ARBAGE#OLLECTORGC PROGRAMMERYOUARE YOUCANTCONTROLEVERYTHING7HENYOUWRITEARISKYMETHOD YOUNEED
9 RECLAIMSTHEMEMORY7ELLLOOKATHOWOBJECTSARECREATED WHERETHEYLIVE ANDHOWTO
11 CODETOHANDLETHEBADTHINGSTHATMIGHTHAPPEN"UTHOWDOYOUKNOWWHENAMETHODIS
KEEPORABANDONTHEMEFFICIENTLY4HATMEANSWELLTALKABOUTTHEHEAP THESTACK SCOPE RISKY7HEREDOYOUPUTTHECODETOHANDLETHEEXCEPTIONALSITUATION)NTHISCHAPTER WERE
CONSTRUCTORS SUPERCONSTRUCTORS NULLREFERENCES ANDGCELIGIBILITY GOINGTOBUILDA-)$)-USIC0LAYER THATUSESTHERISKY*AVA3OUND!0) SOWEBETTERFINDOUT

The stack and the heap, where objects and variables live 236 Making a music machine (the BeatBox) 316
calls
When someone od, this Methods on the stack 237 What if you need to call risky code? 319
s an exceptio
the go() meth ned. His Where local variables live 238 h row n

t
2 ba
ck Exceptions say “something bad may have happened...” 320
Duck is abando has been
Where instance variables live 239 The compiler guarantees (it checks) that you’re aware of the risks 321
only reference for a
The miracle of object creation 240 Catching exceptions using a try/catch (skateboarder) 322
class Cow {
class Bar { void moo() {
reprogrammed k.

t
ent Duc void go() { if (serverDown){
Constructors (the code that runs when you say new) 241 moo(); explode();
Du ec differ }
ck bj }
Flow control in try/catch blocks 326
}
o int stuff() {
1 }
x.beep();
Initializing the state of a new Duck 243 } calls risky method The finally block (no matter what happens, turn off the oven!) 327
d }

Overloaded constructors 247 Catching multiple exceptions (the order matters) 329
Heap your code class with a

t
Du
ck objec
Superclass constructors (constructor chaining) 250 risky method Declaring an exception (just duck it) 335
Invoking overloaded constructors using this() 256 Handle or declare law 337
g the
‘d’ is assigned a new Duck object, leavin. That Life of an object 258 Code Kitchen (making sounds) 339
original (first) Duck object abandoned Garbage Collection (and making objects eligible) 260 Exercises and puzzles 348
first Duck is toast..
Exercises and puzzles 266

A Very Graphic Story


Numbers Matter Face it, you need to make GUIs. %VENIFYOUBELIEVETHATFORTHERESTOFYOUR
Do the Math.4HE*AVA!0)HASMETHODSFORABSOLUTEVALUE ROUNDING MINMAX ETC LIFEYOULLWRITEONLYSERVER SIDECODE SOONERORLATERYOULLNEEDTOWRITETOOLS ANDYOULL
Static variables
10 "UTWHATABOUTFORMATTING9OUMIGHTWANTNUMBERSTOPRINTEXACTLYTWODECIMALPOINTS
12 WANTAGRAPHICALINTERFACE7ELLSPENDTWOCHAPTERSON'5)S ANDLEARNMORELANGUAGE
are shared by ORWITHCOMMASINALLTHERIGHTPLACES!NDYOUMIGHTWANTTOPRINTANDMANIPULATEDATES FEATURESINCLUDING%VENT(ANDLINGAND)NNER#LASSES7ELLPUTABUTTONONTHESCREEN
all instances of TOO!NDWHATABOUTPARSINGA3TRINGINTOANUMBER/RTURNINGANUMBERINTOA3TRING class MyOuter { WELLPAINTONTHESCREEN WELLDISPLAYAJPEGIMAGE ANDWELLEVENDOSOMEANIMATION
a class.
7ELLSTARTBYLEARNINGWHATITMEANSFORAVARIABLEORMETHODTOBESTATIC
static variable: class MyInner {
void go() { Your first GUI 355
iceCream Math class (do you really need an instance of it?) 274 }
kid instance two Getting a user event 357
}
kid instance one static methods 275 Implement a listener interface 358
static variables 277 }
instance variables: Getting a button’s ActionEvent 360
one per instance Constants (static final variables) 282 Putting graphics on a GUI 363
The outer and inner objects
Math methods (random(), round(), abs(), etc.) 286 Fun with paintComponent() 365
static variables: are now intimately linked.
r

one per class Wrapper classes (Integer, Boolean, Character, etc.) 287 oute The Graphics2D object 366
Autoboxing 289 Putting more than one button on a screen 370
Number formatting 294
jects on the inner
These two aobspecial bond. The Inner classes to the rescue (make your listener an inner class) 376
Date formatting and manipulation 301 heap have use the outer’s
Animation (move it, paint it, move it, paint it, move it, paint it...) 382
inner can (and vice-versa).
Static imports 307 variables Code Kitchen (painting graphics with the beat of the music) 386
Exercises and puzzles 310 Exercises and puzzles 394

xiv xv
Work on your Swing Make a Connection
Swing is easy. 5NLESSYOUACTUALLYCAREWHEREEVERYTHINGGOES3WINGCODELOOKS Connect with the outside world. )TSEASY!LLTHELOW LEVELNETWORKING
EASY BUTTHENCOMPILEIT RUNIT LOOKATITANDTHINK hHEY THATSNOTSUPPOSEDTOGOTHEREv DETAILSARETAKENCAREOFBYCLASSESINTHEJAVANETLIBRARY/NEOF*AVASBESTFEATURESIS
4HETHINGTHATMAKESITEASYTOCODEISTHETHINGTHATMAKESITHARDTOCONTROLˆTHE,AYOUT
13 15 THATSENDINGANDRECEIVINGDATAOVERANETWORKISREALLYJUST)/WITHASLIGHTLYDIFFERENT
-ANAGER"UTWITHALITTLEWORK YOUCANGETLAYOUTMANAGERSTOSUBMITTOYOURWILL)N CONNECTIONSTREAMATTHEENDOFTHECHAIN)NTHISCHAPTERWELLMAKECLIENTSOCKETS7ELL
THISCHAPTER WELLWORKONOUR3WINGANDLEARNMOREABOUTWIDGETS MAKESERVERSOCKETS7ELLMAKECLIENTSANDSERVERS"EFORETHECHAPTERSDONE YOULLHAVEA
FULLY FUNCTIONAL MULTITHREADEDCHATCLIENT$IDWEJUSTSAYMULTITHREADED
Swing Components 400 Socket co
Components in Layout Managers (they control size and placement) 401 to port 50nnection
on the serv 00 Chat program overview 473
the east and Three Layout Managers (border, flow, box) 403 er at
Connecting, sending, and receiving 474
196.164.1.10
3
west get theirth. BorderLayout (cares about five regions) 404
preferred wid Network sockets 475
FlowLayout (cares about the order and preferred size) 408
TCP ports 476
Things in the BoxLayout (like flow, but can stack components vertically) 411
Reading data from a socket (using BufferedReader) 478
north and The center get JTextField (for single-line user input) 413
south get their Writing data to a socket (using PrintWriter) 479
whatever’s left.s JTextArea (for multi-line, scrolling text) 414 Client Server
preferred height. nnection Writing the Daily Advice Client program 480
JCheckBox (is it selected?) 416
Writing a simple server 483
Socket ocothe client
JList (a scrollable, selectable list) 417 back t 164.1.100,
at 196. 242 Daily Advice Server code 484
Code Kitchen (The Big One - building the BeatBox chat client) 418 port 4 Writing a chat client 486
Exercises and puzzles 424
Multiple call stacks 490
Launching a new thread (make it, start it) 492
The Runnable interface (the thread’s job) 494
Saving Objects Three states of a new Thread object (new, runnable, running) 495
Objects can be flattened and inflated. /BJECTSHAVESTATEANDBEHAVIOR The runnable-running loop 496
"EHAVIORLIVESINTHECLASS BUTSTATELIVESWITHINEACHINDIVIDUALOBJECT)FYOURPROGRAM Thread scheduler (it’s his decision, not yours) 497
Putting a thread to sleep 501
14 NEEDSTOSAVESTATE YOUCANDOITTHEHARDWAY INTERROGATINGEACHOBJECT PAINSTAKINGLY
WRITINGTHEVALUEOFEACHINSTANCEVARIABLE/R YOUCANDOITTHEEASY//WAYˆYOUSIMPLY Making and starting two threads 503
FREEZE DRYTHEOBJECTSERIALIZEIT ANDRECONSTITUTEDESERIALIZE ITTOGETITBACK Concurrency issues: can this couple be saved? 505
The Ryan and Monica concurrency problem, in code 506
Saving object state 431
serialized Locking to make things atomic 510
Writing a serialized object to a file 432
Every object has a lock 511
Java input and output streams (connections and chains) 433
The dreaded “Lost Update” problem 512
Object serialization 434
ions? Synchronized methods (using a lock) 514
Implementing the Serializable interface 437
Any quest Deadlock! 516
Using transient variables 439
Multithreaded ChatClient code 518
deserialized Deserializing an object 441
Ready-bake SimpleChatServer 520
Writing to a text file 447
Exercises and puzzles 524
java.io.File 452
Reading from a text file 454
Splitting a String into tokens with split() 458
CodeKitchen 462
Exercises and puzzles 466
xvi xvii
Data Structures Distributed Computing
Sorting is a snap in Java. 9OUHAVEALLTHETOOLSFORCOLLECTINGANDMANIPULATING Being remote doesn’t have to be a bad thing. 3URE THINGSAREEASIER
YOURDATAWITHOUTHAVINGTOWRITEYOUROWNSORTALGORITHMS4HE*AVA#OLLECTIONS WHENALLTHEPARTSOFYOURAPPLICATIONAREINONEPLACE INONEHEAP WITHONE*6-TORULE
16 &RAMEWORKHASADATASTRUCTURETHATSHOULDWORKFORVIRTUALLYANYTHINGYOULLEVERNEED
18 THEMALL"UTTHATSNOTALWAYSPOSSIBLE/RDESIRABLE7HATIFYOURAPPLICATIONHANDLES
TODO7ANTTOKEEPALISTTHATYOUCANEASILYKEEPADDINGTO7ANTTOFINDSOMETHINGBY POWERFULCOMPUTATIONS7HATIFYOURAPPNEEDSDATAFROMASECUREDATABASE)NTHIS
NAME7ANTTOCREATEALISTTHATAUTOMATICALLYTAKESOUTALLTHEDUPLICATES3ORTYOURCO CHAPTER WELLLEARNTOUSE*AVASAMAZINGLYSIMPLE2EMOTE-ETHOD)NVOCATION2-) 7ELL
WORKERSBYTHENUMBEROFTIMESTHEYVESTABBEDYOUINTHEBACK ALSOTAKEAQUICKPEEKAT3ERVLETS %NTERPRISE*AVA"EANS%*" AND*INI

Collections 533 Server Java Remote Method Invocation (RMI), hands-on, very detailed 614
Client
Sorting an ArrayList with Collections.sort() 534 Servlets (a quick look) 625
List 0 1 2 3 Generics and type-safety 540 RMI STUB RMI SKELETON Enterprise JavaBeans (EJB), a very quick look 631
Sorting things that implement the Comparable interface 547 Jini, the best trick of all 632

r
e

t
Cli Se Se
Sorting things with a custom Comparator 552 ent helper rvice help
C li
rvice objec Building the really cool universal service browser 636
ent object
The collection API—lists, sets, and maps 557 The End 648
Set Avoiding duplicates with HashSet 559
Overriding hashCode() and equals() 560
HashMap 567
Using wildcards for polymorphism 574
“Ball1”
Map “Ball” “Ball2”
“Fish” “Car”
“Fish”“Car” Appendix A
Exercises and puzzles 576
The final Code Kitchen project. !LLTHECODEFORTHEFULLCLIENT SERVERCHAT
BEATBOX9OURCHANCETOBEAROCKSTAR
Release Your Code
It’s time to let go. 9OUWROTEYOURCODE9OUTESTEDYOURCODE9OUREFINEDYOURCODE
A
BeatBoxFinal (client code) 650
9OUTOLDEVERYONEYOUKNOWTHATIFYOUNEVERSAWALINEOFCODEAGAIN THATDBEFINE"UTIN MusicServer (server code) 657
DANCEBEAT
17 THEEND YOUVECREATEDAWORKOFART4HETHINGACTUALLYRUNS"UTNOWWHAT)NTHESEFINAL

TWOCHAPTERS WELLEXPLOREHOWTOORGANIZE PACKAGE ANDDEPLOYYOUR*AVACODE7ELLLOOK !NDYGROOVE
REVISED
#HRISGROOVE
BEAT
.IGELDANCE
ATLOCAL SEMI LOCAL ANDREMOTEDEPLOYMENTOPTIONSINCLUDINGEXECUTABLEJARS *AVA7EB
3TART 2-) AND3ERVLETS2ELAX3OMEOFTHECOOLESTTHINGSIN*AVAAREEASIERTHANYOUTHINK
classes

Deployment options 582


com
Keep your source code and class files separate 584 Appendix B
101101
10 110 1 Making an executable JAR (Java ARchives) 585
0 11 0
001 10
MyApp.jar
foo
001 01

Running an executable JAR 586 The Top Ten Things that didn’t make it into the book. 7ECANTSEND
MyApp.class
Put your classes in a package! 587 YOUOUTINTOTHEWORLDJUSTYET 7EHAVEAFEWMORETHINGSFORYOU BUTTHISISTHEENDOFTHE
Packages must have a matching directory structure 589
B BOOK!NDTHISTIMEWEREALLYMEANIT

Web Server Compiling and running with packages 590 Top Ten List 660
JWS
Lorper
iure
Compiling with -d 591
eugue
tat vero
conse
euguero- Making an executable JAR (with packages) 592
MyApp.jar
MyApp.jnlp MyApp.jar
Java Web Start (JWS) for deployment from the web 597
How to make and deploy a JWS application 600 Index 677
Exercises and puzzles 601

xviii xix
i
once upon a time in Objectville

Chair Wars
2 classes and objects (or How Objects Can Change Your Life)
the spec
NCEUPONATIMEINASOFTWARESHOP TWO
PROGRAMMERSWEREGIVENTHESAMESPECANDTOLDTO
A Trip to Objectville hBUILDITv4HE2EALLY!NNOYING0ROJECT-ANAGER
O FORCEDTHETWOCODERSTOCOMPETE
BYPROMISINGTHATWHOEVERDELIVERS
lRSTGETSONEOFTHOSECOOL!ERON©
CHAIRSALLTHE3ILICON6ALLEYGUYSHAVE
,ARRY THEPROCEDURALPROGRAMMER AND
We’re going to "RAD THE//GUY BOTHKNEWTHISWOULD
Objectville! We’re BEAPIECEOFCAKE
leaving this dusty ol’
procedural town for good. ,ARRY SITTINGINHISCUBE THOUGHTTO
I’ll send you a postcard. HIMSELF h7HATARETHETHINGSTHISPROGRAM
HASTODO7HATPROCEDURESDOWENEEDv
!NDHEANSWEREDHIMSELF hROTATEAND
PLAY3OUNDv3OOFFHEWENTTOBUILDTHE
PROCEDURES!FTERALL WHATISAPROGRAMIFNOT
APILEOFPROCEDURES
"RAD MEANWHILE KICKEDBACKATTHECAFE
ANDTHOUGHTTOHIMSELF h7HATARETHETHINGS
INTHISPROGRAMWHOARETHEKEYPLAYERSv(E
lRSTTHOUGHTOF4HE3HAPES/FCOURSE THERE
WEREOTHEROBJECTSHETHOUGHTOFLIKETHE5SER THE3OUND
ANDTHE#LICKINGEVENT"UTHEALREADYHADALIBRARYOFCODE
FORTHOSEPIECES SOHEFOCUSEDONBUILDING3HAPES2EAD
ONTOSEEHOW"RADAND,ARRYBUILTTHEIRPROGRAMS AND the chair
FORTHEANSWERTOYOURBURNINGQUESTION h3O WHOGOTTHE
!ERONv
I was told there would be objects. )NCHAPTER WEPUTALLOFOURCODEINTHE
MAIN METHOD4HATSNOTEXACTLYOBJECT ORIENTED)NFACT THATSNOTOBJECT ORIENTEDATALL7ELL In Larry’s cube At Brad’s laptop at the cafe
WEDIDUSEAFEWOBJECTS LIKETHE3TRINGARRAYSFORTHE0HRASE / -ATIC BUTWEDIDNTACTUALLY !SHEHADDONEAGAZILLIONTIMESBEFORE ,ARRY "RADWROTEACLASSFOREACHOFTHETHREESHAPES
DEVELOPANYOFOUROWNOBJECTTYPES3ONOWWEVEGOTTOLEAVETHATPROCEDURALWORLDBEHIND SETABOUTWRITINGHIS)MPORTANT0ROCEDURES
(EWROTEROTATEANDPLAY3OUNDINNOTIME
GETTHEHECKOUTOFMAIN ANDSTARTMAKINGSOMEOBJECTSOFOUROWN7ELLLOOKATWHATMAKES
rotate(shapeNum) {
OBJECT ORIENTED// DEVELOPMENTIN*AVASOMUCHFUN7ELLLOOKATTHEDIFFERENCEBETWEEN // make the shape rotate 360º
ACLASSANDANOBJECT7ELLLOOKATHOWOBJECTSCANGIVEYOUABETTERLIFEATLEASTTHEPROGRAM }
MINGPARTOFYOURLIFE.OTMUCHWECANDOABOUTYOURFASHIONSENSE 7ARNINGONCEYOUGET playSound(shapeNum) {
// use shapeNum to lookup which }
TO/BJECTVILLE YOUMIGHTNEVERGOBACK3ENDUSAPOSTCARD
// AIF sound to play, and play it
}
}
}

this is a new chapter 27 28 chapter 2


classes and objects once upon a time in Objectville

Larry thought he’d nailed it. He could almost feel the rolled Larry snuck in just moments ahead of Brad.
steel of the Aeron beneath his... (AH3OMUCHFORTHATFOOFY//NONSENSE "UTTHESMIRKON,ARRYSFACEMELTEDWHENTHE
2EALLY!NNOYING0ROJECT-ANAGERSAIDWITHTHATTONEOFDISAPPOINTMENT h/H NO THATSNOT
But wait! There’s been a spec change. HOWTHEAMOEBAISSUPPOSEDTOROTATEv
h/+ TECHNICALLYYOUWERElRST ,ARRY vSAIDTHE-ANAGER hBUTWEHAVETOADDJUSTONE 4URNSOUT BOTHPROGRAMMERSHADWRITTENTHEIRROTATECODELIKETHIS
TINYTHINGTOTHEPROGRAM)TLLBENOPROBLEMFORCRACKPROGRAMMERSLIKEYOUTWOv 1) determine the rectangle that surrounds the shape
h)F)HADADIMEFOREVERYTIME)VEHEARDTHATONEv THOUGHT,ARRY KNOWINGTHATSPEC 2) calculate the center of that rectangle, and rotate the shape around that point.
CHANGE NO PROBLEMWASAFANTASYh!NDYET"RADLOOKSSTRANGELYSERENE7HATSUPWITH "UTTHEAMOEBASHAPEWASSUPPOSEDTOROTATEAROUNDAPOINTONONEEND LIKEACLOCKHAND
THATv3TILL ,ARRYHELDTIGHTTOHISCOREBELIEFTHATTHE//WAY WHILECUTE WASJUST
SLOW!NDTHATIFYOUWANTEDTOCHANGEHISMIND YOUDHAVETOPRYITFROMHISCOLD h)MTOASTvTHOUGHT,ARRY VISUALIZINGCHARRED7ONDERBREAD©h!LTHOUGH HMMMM)COULD
DEAD CARPAL TUNNELLEDHANDS JUSTADDANOTHERIFELSETOTHEROTATEPROCEDURE ANDTHENJUSTHARD CODETHEROTATIONPOINT
CODEFORTHEAMOEBA4HATPROBABLYWONTBREAKANYTHINGv"UTTHELITTLEVOICEATTHEBACKOF
ape HISHEADSAID h"IG-ISTAKE$OYOUHONESTLYTHINKTHESPECWONTCHANGEAGAINv
moeba sh s.
l be an a
There wil en, with the other what got added to the spec
re
on the sc ser clicks on the L arry
eu the point in
When th tate like rotation
it will ro if sound file  Ameoba version:
amoeba, .h ’s
nd play a and Brad
others, a What the spec conveniently
forgot to mention

rotation
e ameba
Where th be:
t sh ou ld
poin

Back in Larry’s cube At Brad’s laptop at the beach Back in Larry’s cube At Brad’s laptop on his lawn
4HEROTATEPROCEDUREWOULDSTILLWORKTHECODEUSED "RADSMILED SIPPEDHISMARGARITA ANDWROTEONE (ElGUREDHEBETTERADDROTATIONPOINTARGUMENTS chair at the Telluride Bluegrass Festival
ALOOKUPTABLETOMATCHASHAPE.UMTOANACTUAL NEWCLASS3OMETIMESTHETHINGHELOVEDMOST TOTHEROTATEPROCEDURE!LOTOFCODEWASAFFECTED 7ITHOUTMISSINGABEAT "RADMODIlEDTHEROTATE
SHAPEGRAPHIC"UTPLAY3OUNDWOULDHAVETOCHANGE ABOUT//WASTHATHEDIDNTHAVETOTOUCHCODE 4ESTING RECOMPILING THEWHOLENINEYARDSALLOVER METHOD BUTONLYINTHE!MOEBACLASS(ENEVER
!NDWHATTHEHECKISAHIFlLE HEDALREADYTESTEDANDDELIVEREDh&LEXIBILITY AGAIN4HINGSTHATUSEDTOWORK DIDNT TOUCHEDTHETESTED WORKING
playSound(shapeNum) { EXTENSIBILITY vHEMUSED REmECTINGONTHE rotate(shapeNum, xPt, yPt) { COMPILEDCODEFORTHEOTHER Amoeba
// if the shape is not an amoeba, BENElTSOF// PARTSOFTHEPROGRAM4O int xPoint
Amoeba // if the shape is not an amoeba,
// use shapeNum to lookup which GIVETHE!MOEBAAROTA int yPoint
// AIF sound to play, and play it // calculate the center point
rotate() { TIONPOINT HEADDEDAN rotate() {
// else // code to rotate an amoeba // based on a rectangle,
// play amoeba .hif sound
ATTRIBUTETHATALL!MOEBAS // code to rotate an amoeba
} // then rotate WOULDHAVE(EMODI // using amoeba’s x and y
}
playSound() { // else lED TESTED ANDDELIVERED }
)TTURNEDOUTNOTTOBESUCHABIGDEAL BUTITSTILL
// code to play the new // use the xPt and yPt as WIRELESSLY THEREVISED playSound() {
MADEHIMQUEASYTOTOUCHPREVIOUSLY TESTEDCODE/F // .hif file for an amoeba
// the rotation point offset PROGRAMDURINGASINGLE // code to play the new
ALLPEOPLE HESHOULDKNOWTHATNOMATTERWHATTHE } // .hif file for an amoeba
PROJECTMANAGERSAYS THESPECALWAYSCHANGES // and then rotate "ELA&LECKSET
}
}
you are here4 29 30 chapter 2
classes and objects once upon a time in Objectville

So, Brad the OO guy got the chair, right ? What about the Amoeba rotate()?
.OTSOFAST,ARRYFOUNDAmAWIN"RADSAPPROACH!ND ,!2297ASNTTHATTHEWHOLEPROBLEMHEREˆTHATTHEAMOEBASHAPE
SINCEHEWASSURETHATIFHEGOTTHECHAIRHEDALSOGET,UCY HADACOMPLETELYDIFFERENTROTATEANDPLAY3OUNDPROCEDURE
INACCOUNTING HEHADTOTURNTHISTHINGAROUND "2!$-ETHOD ve
rride Now

O
,!2299OUVEGOTDUPLICATEDCODE4HEROTATE ,!2297HATEVER(OWCANAMOEBADOSOMETHINGDIFFERENTIF
PROCEDUREISINALLFOUR3HAPETHINGS As w
IThINHERITSvITSFUNCTIONALITYFROMTHE3HAPECLASS k Me Ho
"2!$)TSAMETHOD NOTAPROCEDURE!NDTHEYRECLASSES "2!$4HATSTHELASTSTEP4HE!MOEBACLASSOVERRIDESTHE
NOTTHINGS METHODSOFTHE3HAPECLASS4HENATRUNTIME THE*6-KNOWSEXACTLY
,!2297HATEVER)TSASTUPIDDESIGN9OUHAVETO WHICHROTATE METHODTORUNWHENSOMEONETELLSTHE!MOEBATOROTATE
MAINTAINFOURDIFFERENTROTATEhMETHODSv(OWCANTHAT
EVERBEGOOD
"2!$/H )GUESSYOUDIDNTSEETHElNALDESIGN,ETME superclass Shape 4
(more abstract)
SHOWYOUHOW//INHERITANCEWORKS ,ARRY rotate() override
playSound()
I Imade
madethe
theAmoeba
Amoebaclass
classoverride
What Larry wanted the
therotate() and playSound()
rotate()method of the
(figured the chair would impress her) superclass the superclass Shape.
methods ofShape.
subclasses Overriding just
(more specific) Overriding just means
meansthat
thataa
subclass
subclassredefines
redefinesone
oneof its
ofits
1 inherited
inheritedmethods
methodswhen needs
whenititneeds
Square Circle Triangle Amoeba Square Circle Triangle Amoeba behavior
I looked at what all four totochange
changeor
orextend
extendthe
thebehavior
rotate() rotate() rotate() rotate() classes have in common. ofofthat method.
thatmethod.
rotate() {
playSound() playSound() playSound() playSound() // amoeba-specific
// rotate code {
Overriding methods
playSound() {
// amoeba-specific
// sound code {
2
They’re Shapes, and they all rotate and Shape
I can take
playSound. So I abstracted out the ,!229(OWDOYOUhTELLvAN!MOEBATO
rotate() 3 care of myself.
common features and put them into a playSound() DOSOMETHING$ONTYOUHAVETOCALLTHE I know how an Amoeba
new class called Shape. PROCEDURE SORRYˆMETHOD ANDTHENTELLIT I know how a Shape is is supposed to rotate
Shape Then I linked the other WHICHTHINGTOROTATE and play a sound.
supposed to behave. Your
superclass four shape classes to job is to tell me what to
rotate() "2!$4HATSTHEREALLYCOOLTHINGABOUT//
playSound() the new Shape class, do, and my job is to make it happen.
7HENITSTIMEFOR SAY THETRIANGLETOROTATE Don’t you worry your little program-
in a relationship called THEPROGRAMCODEINVOKESCALLS THEROTATE mer head about how I do it.
inheritance. METHODONTHETRIANGLEOBJECT4HERESTOFTHE
You can read this as, “Square inherits from Shape”,
PROGRAMREALLYDOESNTKNOWORCAREHOWTHE
“Circle inherits from Shape”, and so on. I removed subclasses
rotate() and playSound() from the other shapes, so now
TRIANGLEDOESIT!NDWHENYOUNEEDTOADD
there’s only one copy to maintain. SOMETHINGNEWTOTHEPROGRAM YOUJUSTWRITE
Square Circle Triangle Amoeba ANEWCLASSFORTHENEWOBJECTTYPE SOTHENEW
The Shape class is called the superclass of the other four
OBJECTSWILLHAVETHEIROWNBEHAVIOR
classes. The other four are the subclasses of Shape. The
subclasses inherit the methods of the superclass. In other
words, if the Shape class has the functionality, then the
subclasses automatically get that same functionality.
you are here4 31 32 chapter 2
classes and objects thinking about objects

The suspense is killing me. When you design a class, think about the objects that
Who got the chair? will be cre ated from that class t ype. Think about:
Nthings the object knows
!MYFROMTHESECONDmOOR
Nthings the object does
UNBEKNOWNSTTOALL THE0ROJECT
-ANAGERHADGIVENTHESPECTO Button Alarm
ShoppingCart
THREEPROGRAMMERS
label alarmTime
cartContents knows color knows alarmMode knows
setColor() setAlarmTime()
addToCart() does setLabel() does getAlarmTime()
setAlarm() does
YiX`e removeFromCart() dePress() isAlarmSet()
checkOut() unDepress() snooze()
What do you like about OO? gfn\i
4IMETOPUMPSOMENEURONS
“It helps me design in a more natural way. Things 9OUJUSTREADASTORYBOUTAPROCEDURAL
have a way of evolving.” PROGRAMMERGOINGHEAD TO HEADWITHAN//
PROGRAMMER9OUGOTAQUICKOVERVIEWOFSOME Things an object knows about itself are called Song
-Joy, 27, software architect
KEY//CONCEPTSINCLUDINGCLASSES METHODS AND instance
ATTRIBUTES7ELLSPENDTHERESTOFTHECHAPTER Ninstance variables title knows
LOOKINGATCLASSESANDOBJECTSWELLRETURNTO variables artist
“Not messing around with code I’ve already
tested, just to add a new feature.” INHERITANCEANDOVERRIDINGINLATERCHAPTERS  (state)
setTitle()
-Brad, 32, programmer "ASEDONWHATYOUVESEENSOFARANDWHATYOU Things an object can do are called methods setArtist() does
MAYKNOWFROMAPREVIOUS//LANGUAGEYOUVE (behavior) play()
WORKEDWITH TAKEAMOMENTTOTHINKABOUT Nmethods
“I like that the data and the methods that oper-
THESEQUESTIONS
ate on that data are together in one class.”
-Josh, 22, beer drinker 7HATARETHEFUNDAMENTALTHINGSYOUNEEDTO
THINKABOUTWHENYOUDESIGNA*AVACLASS7HAT
“Reusing code in other applications. When I write ARETHEQUESTIONSYOUNEEDTOASKYOURSELF 4HINGSANOBJECTKNOWSABOUTITSELFARECALLEDINSTANCE Sharpen your pencil
a new class, I can make it flexible enough to be )FYOUCOULDDESIGNACHECKLISTTOUSEWHEN VARIABLES4HEYREPRESENTANOBJECTSSTATETHEDATA AND
used in something new, later.” YOUREDESIGNINGACLASS WHATWOULDBEONTHE
-Chris, 39, project manager
CANHAVEUNIQUEVALUESFOREACHOBJECTOFTHATTYPE &ILLINWHATATELEVISIONOBJECT
CHECKLIST MIGHTNEEDTOKNOWANDDO
Think of instance as another way of saying object.
“I can’t believe Chris just said that. He hasn’t 4HINGSANOBJECTCANDOARECALLEDMETHODS7HENYOU
written a line of code in 5 years.” DESIGNACLASS YOUTHINKABOUTTHEDATAANOBJECTWILLNEED
-Daryl, 44, works for Chris metacognitive tip TOKNOWABOUTITSELF ANDYOUALSODESIGNTHEMETHODS
THATOPERATEONTHATDATA)TSCOMMONFORANOBJECTTO
If you’re stuck on an exercise, try talking about HAVEMETHODSTHATREADORWRITETHEVALUESOFTHEINSTANCE
“Besides the chair?”
it out loud. Speaking (and hearing) activates VARIABLES&OREXAMPLE !LARMOBJECTSHAVEANINSTANCE
-Amy, 34, programmer
a different part of your brain. Although it VARIABLETOHOLDTHEALARM4IME ANDTWOMETHODSFOR
works best if you have another person to
GETTINGANDSETTINGTHEALARM4IME
discuss it with, pets work too. That’s how
our dog learned polymorphism. 3OOBJECTSHAVEINSTANCEVARIABLESANDMETHODS BUTTHOSE
INSTANCEVARIABLESANDMETHODSAREDESIGNEDASPARTOFTHE
CLASS

you are here4 33 34 chapter 2


classes and objects making objects

Making your first object


3OWHATDOESITTAKETOCREATEANDUSEANOBJECT9OUNEEDTWOCLASSES/NE
What’s the difference between CLASSFORTHETYPEOFOBJECTYOUWANTTOUSE$OG !LARM#LOCK 4ELEVISION The Dot Operator (.)
ETC ANDANOTHERCLASSTOTESTYOURNEWCLASS4HETESTERCLASSISWHEREYOUPUT
a class and an object? THEMAINMETHOD ANDINTHATMAIN METHODYOUCREATEANDACCESSOBJECTS 4HEDOTOPERATOR GIVES
OFYOURNEWCLASSTYPE4HETESTERCLASSHASONLYONEJOBTOTRYOUTTHEMETH YOUACCESSTOANOBJECTS
ODSANDVARIABLESOFYOURNEWOBJECTCLASSTYPE STATEANDBEHAVIORINSTANCE
VARIABLESANDMETHODS 
&ROMTHISPOINTFORWARDINTHEBOOK YOULLSEETWOCLASSESINMANYOF
OUREXAMPLES/NEWILLBETHEREALCLASSnTHECLASSWHOSEOBJECTSWE
REALLYWANTTOUSE ANDTHEOTHERCLASSWILLBETHETESTERCLASS WHICHWE MAKEANEWOBJECT
CALLWHATEVER9OUR#LASS.AME)STestDrive&OREXAMPLE IFWEMAKEA $OGDNEW$OG 
A class is not an object. Bungee CLASS WELLNEEDABungeeTestDriveCLASSASWELL/NLYTHE
SOME#LASS.AMETestDrive CLASSWILLHAVEAMAIN METHOD ANDITSSOLE
(but it’s used to construct them) TELLITTOBARKBYUSINGTHE
PURPOSEISTOCREATEOBJECTSOFYOURNEWTYPETHENOT THE TESTERCLASS AND
THENUSETHEDOTOPERATOR TOACCESSTHEMETHODSANDVARIABLESOFTHENEW DOTOPERATORONTHE
!CLASSISABLUEPRINTFORANOBJECT)TTELLSTHE VARIABLEDTOCALLBARK
JVM OBJECTS4HISWILLALLBEMADESTUNNINGLYCLEARBYTHEFOLLOWINGEXAMPLES
VIRTUALMACHINEHOWTOMAKEANOBJECTOFTHAT DBARK 
PARTICULARTYPE%ACHOBJECTMADEFROMTHAT
CLASSCANHAVEITSOWNVALUESFORTHE 1 Write your class
SETITSSIZEUSINGTHE
INSTANCEVARIABLESOFTHATCLASS&OR DOTOPERATOR
class Dog {
EXAMPLE YOUMIGHTUSETHE"UTTON DOG DSIZE
instance va
CLASSTOMAKEDOZENSOFDIFFERENT riables
class int size; size
BUTTONS ANDEACHBUTTONMIGHTHAVE String breed; breed
ITSOWNCOLOR SIZE SHAPE LABEL ANDSOON name
String name;
a method bark()
void bark() {
System.out.println(“Ruff! Ruff!”);
}
} 2 Write a tester (TestDrive) class
class DogTestDrive {
Look at it this way... !NOBJECTISLIKEONEENTRYINYOURADDRESSBOOK hod
ain met public static void main (String[] args) {
/NEANALOGYFOROBJECTSISAPACKETOFUNUSED2OLODEX»CARDS just a m na put codeep) // Dog test code goes here
%ACHCARDHASTHESAMEBLANKFIELDSTHEINSTANCEVARIABLES 7HEN on st }
(we’rite gin the next
YOUFILLOUTACARDYOUARECREATINGANINSTANCEOBJECT ANDTHE in }
ENTRIESYOUMAKEONTHATCARDREPRESENTITSSTATE
4HEMETHODSOFTHECLASSARETHETHINGSYOUDOTOAPARTICULARCARD In your tester, make an object and access
GET.AME CHANGE.AME SET.AME COULDALLBEMETHODSFOR 3 the object’s variables and methods
CLASS2OLODEX
class DogTestDrive {
3O EACHCARDCANDOTHESAMETHINGSGET.AME CHANGE.AME
public static void main (String[] args) {
ETC BUTEACHCARDKNOWSTHINGSUNIQUETOTHATPARTICULARCARD
Dog d = new Dog(); make a Dog
object
d.size = 40; use the dot operator (.)
d.bark();
If you already have some OO savvy,
dot r to set the size of the Do
operato } g
and to call its bark you’ll know we’re not using encapsulation.
} () method We’ll get there in chapter 4.

you are here4 35 36 chapter 2


classes and objects get the heck out of main

Making and testing Movie objects Quick! Get out of main!


!SLONGASYOUREINMAIN YOURENOTREALLYIN/BJECTVILLE)TSlNEFORATEST
class Movie {
String title;
PROGRAMTORUNWITHINTHEMAINMETHOD BUTINATRUE//APPLICATION YOU
String genre; NEEDOBJECTSTALKINGTOOTHEROBJECTS ASOPPOSEDTOASTATICMAIN METHOD
int rating; CREATINGANDTESTINGOBJECTS

void playIt() {
System.out.println(“Playing the movie”);
} The t wo uses of main:
}
Nto test your real class
public class MovieTestDrive {
Nto launch/start your Java application
public static void main(String[] args) {
Movie one = new Movie(); !REAL*AVAAPPLICATIONISNOTHINGBUTOBJECTSTALKINGTOOTHEROBJECTS)NTHIS
one.title = “Gone with the Stock”; CASE TALKINGMEANSOBJECTSCALLINGMETHODSONONEANOTHER/NTHEPREVIOUS
one.genre = “Tragic”; PAGE ANDINCHAPTER WELOOKATUSINGAMAIN METHODFROMASEPARATE
one.rating = -2; 4EST$RIVECLASSTOCREATEANDTESTTHEMETHODSANDVARIABLESOFANOTHERCLASS)N
Movie two = new Movie(); CHAPTERWELOOKATUSINGACLASSWITHAMAIN METHODTOSTARTTHEBALLROLLING
two.title = “Lost in Cubicle Space”;
ONAREAL*AVAAPPLICATIONBYMAKINGOBJECTSANDTHENTURNINGTHOSEOBJECTS
two.genre = “Comedy”; GameLauncher
LOOSETOINTERACTWITHOTHEROBJECTS ETC
two.rating = 5; make
two.playIt(); !SA@SNEAKPREVIEW THOUGH OFHOWAREAL*AVAAPPLICATIONMIGHTBEHAVE GuessGs a
Movie three = new Movie(); HERESALITTLEEXAMPLE"ECAUSEWERESTILLATTHEEARLIESTSTAGESOFLEARNING*AVA obje ame
three.title = “Byte Club”; WEREWORKINGWITHASMALLTOOLKIT SOYOULLlNDTHISPROGRAMALITTLECLUNKY main(String[] args) tells citt and
three.genre = “Tragic but ultimately uplifting”; ANDINEFlCIENT9OUMIGHTWANTTOTHINKABOUTWHATYOUCOULDDOTOIMPROVE startG to
three.rating = 127; IT ANDINLATERCHAPTERSTHATSEXACTLYWHATWELLDO$ONTWORRYIFSOMEOFTHE ame
} CODEISCONFUSINGTHEKEYPOINTOFTHISEXAMPLEISTHATOBJECTSTALKTOOBJECTS
}
Sharpen your pencil The Guessing Game GuessGame
instan
3UMMARY p1 variab ce
title 4HEGUESSINGGAMEINVOLVESA@GAMEOBJECTANDTHREE@PLAYEROBJECTS4HEGAMEGEN p2 fortheles
MOVIE p3
genre ERATESARANDOMNUMBERBETWEENAND ANDTHETHREEPLAYEROBJECTSTRYTOGUESS players three
title object 1
IT7EDIDNTSAYITWASAREALLYEXCITINGGAME
genre rating startGame()
rating #LASSES
playIt() GuessGame.class Player.class GameLauncher.class
title the
4HE-OVIE4EST$RIVECLASSCREATESOBJECTSINSTANCES OF object 2 genre 4HE,OGIC Player this number
THE-OVIECLASSANDUSESTHEDOTOPERATOR TOSETTHE
guessepdlayer
rating  4HE'AME,AUNCHERCLASSISWHERETHEAPPLICATIONSTARTSITHASTHEMAIN METHOD number
INSTANCEVARIABLESTOASPECIFICVALUE4HE-OVIE4EST$RIVE
CLASSALSOINVOKESCALLS AMETHODONONEOFTHEOBJECTS  )NTHEMAIN METHOD A'UESS'AMEOBJECTISCREATED ANDITSSTART'AME METHOD
&ILLINTHECHARTTOTHERIGHTWITHTHEVALUESTHETHREE ISCALLED guess() meth
title makin od for
OBJECTSHAVEATTHEENDOFMAIN 
 4HE'UESS'AMEOBJECTSSTART'AME METHODISWHERETHEENTIREGAMEPLAYSOUT g u e ss g a
object 3 genre
)TCREATESTHREEPLAYERS THENhTHINKSvOFARANDOMNUMBERTHETARGETFORTHEPLAYERS
rating TOGUESS )TTHENASKSEACHPLAYERTOGUESS CHECKSTHERESULT ANDEITHERPRINTSOUT
INFORMATIONABOUTTHEWINNINGPLAYERS ORASKSTHEMTOGUESSAGAIN

you are here4 37 38 chapter 2


classes and objects Guessing Game

public class GuessGame { GuessGame has ee


Player p1; variables for thethrthr instance Running the Guessing Game
Player p2; objects ee Player
Player p3; public class Player {
int number = 0; // where the guess goes
public void startGame() {
p1 = new Player();
create three Player object
s and public void guess() { /UTPUTITWILLBEDIFFERENTEACHTIMEYOURUNIT
p2 = new Player();
assign them to the
number = (int) (Math.random() * 10);
p3 = new Player(); instance variables three Player File Edit Window Help Explode
System.out.println(“I’m guessing “
int guessp1 = 0; declare three variables to hold the + number); %java GameLauncher
int guessp2 = 0; }
int guessp3 = 0; I’m thinking of a number between 0 and 9...
three guesses the Players make
}
boolean p1isRight = false; Number to guess is 7
boolean p2isRight = false;
declare three variables to hold a true or
public class GameLauncher { I’m guessing 1
boolean p3isRight = false; false based on the player’s answer
public static void main (String[] args) { I’m guessing 9
int targetNumber = (int) (Math.random() * 10); make a ‘target’ number that the GuessGame game = new GuessGame();
System.out.println(“I’m thinking of a number between 0 and 9...”); players have to guess game.startGame(); I’m guessing 9
while(true) { } Player one guessed 1
System.out.println(“Number to guess is “ + targetNumber); }
Player two guessed 9
p1.guess(); Player three guessed 9
p2.guess();
call each player’s guess() method
p3.guess(); Players will have to try again.
Java takes out the
guessp1 = p1.number;
Garbage Number to guess is 7
System.out.println(“Player one guessed “ + guessp1);
I’m guessing 3
guessp2 = p2.number; %ACHTIMEANOBJECTISCREATED
get each player’s guess (the result their
IN*AVA ITGOESINTOANAREAOF I’m guessing 0
System.out.println(“Player two guessed “ + guessp2); guess() method running) by accessingofthe
MEMORYKNOWNAS4HE(EAP I’m guessing 9
guessp3 = p3.number; number variable of each player
!LLOBJECTSˆNOMATTERWHEN WHERE
System.out.println(“Player three guessed “ + guessp3); Player one guessed 3
ORHOWTHEYRECREATEDnLIVEONTHE
if (guessp1 == targetNumber) { HEAP"UTITSNOTJUSTANYOLDMEMORY Player two guessed 0
p1isRight = true; HEAPTHE*AVAHEAPISACTUALLYCALLEDTHE Player three guessed 9
} check each player’s guess to see if it matches 'ARBAGE #OLLECTIBLE(EAP7HENYOU
if (guessp2 == targetNumber) { the target number. If a player is right, CREATEANOBJECT *AVAALLOCATESMEMORY
Players will have to try again.
p2isRight = true; then set that player’s variable to be true SPACEONTHEHEAPACCORDINGTOHOW Number to guess is 7
} (remember, we set it false by default) MUCHTHATPARTICULAROBJECTNEEDS!N I’m guessing 7
if (guessp3 == targetNumber) {
p3isRight = true;
OBJECTWITH SAY INSTANCEVARIABLES
WILLPROBABLYNEEDMORESPACETHANAN I’m guessing 5
}
OBJECTWITHONLYTWOINSTANCEVARIABLES I’m guessing 0
if (p1isRight || p2isRight || p3isRight) { "UTWHATHAPPENSWHENYOUNEEDTO
if player one OR player two OR player three is right..
(the || operator means OR) . Player one guessed 7
RECLAIMTHATSPACE(OWDOYOUGETAN
System.out.println(“We have a winner!”); OBJECTOUTOFTHEHEAPWHENYOUREDONE Player two guessed 5
System.out.println(“Player one got it right? “ + p1isRight);
WITHIT*AVAMANAGESTHATMEMORY Player three guessed 0
System.out.println(“Player two got it right? “ + p2isRight);
System.out.println(“Player three got it right? “ + p3isRight); FORYOU7HENTHE*6-CAN@SEETHATAN
We have a winner!
System.out.println(“Game is over.”); OBJECTCANNEVERBEUSEDAGAIN THAT
break; // game over, so break out of the loop OBJECTBECOMESELIGIBLEFORGARBAGE Player one got it right? true
COLLECTION!NDIFYOURERUNNINGLOWON Player two got it right? false
} else { otherwise
MEMORY THE'ARBAGE#OLLECTORWILLRUN
// we must keep going because nobody got it right! players fo,rstanay in the loop and as Player three got it right? false
System.out.println(“Players will have to try again.”); other guess. k the THROWOUTTHEUNREACHABLEOBJECTS AND
} // end if/else FREEUPTHESPACE SOTHATTHESPACECAN Game is over.
} // end loop BEREUSED)NLATERCHAPTERSYOULLLEARN
} // end method MOREABOUTHOWTHISWORKS
} // end class

you are here4 39 40 chapter 2


classes and objects exercise: Be the Compiler

there are no
Dumb Questions
1dQ^OU_Q "%THECOMPILER
Q: 7HATIF)NEEDGLOBAL Q: 7HATISA*AVAPROGRAM
VARIABLESANDMETHODS(OW 7HATDOYOUACTUALLYDELIVER Each of the Java files on this page
DO)DOTHATIFEVERYTHINGHASTO represents a complete source file.
GOINACLASS
Your job is to play compiler and
A: !*AVAPROGRAMISAPILE
OFCLASSESORATLEASTONECLASS 
Make it Stic determine whether each of
A: 4HEREISNTACONCEPTOF )NA*AVAAPPLICATION ONEOF
k these files will compile.
@GLOBALVARIABLESANDMETHODSIN THECLASSESMUSTHAVEAMAIN If they won’t compile,
!CLASSISL
A*AVA//PROGRAM)NPRACTICAL METHOD USEDTOSTART UPTHE IKEARECIPE
 how would you fix them,
USE HOWEVER THEREARETIMES PROGRAM3OASAPROGRAMMER /BJEC TSA
RELIKE
WHENYOUWANTAMETHODOR YOUWRITEONEORMORECLASSES COOKIES and if they do compile,
ACONSTANT TOBEAVAILABLE !NDTHOSECLASSESAREWHATYOU what would be their output?
TOANYCODERUNNINGINANY DELIVER)FTHEEND USERDOESNT
PARTOFYOURPROGRAM4HINK HAVEA*6- THENYOULLALSO
OFTHErandom()METHODIN NEEDTOINCLUDETHATWITH
THE0HRASE / -ATICAPPITSA YOURAPPLICATIONSCLASSES A
METHODTHATSHOULDBEC ALLABLE SOTHATTHEYCANRUNYOUR
class TapeDeck {
FROMANYWHERE/RWHATABOUT PROGRAM4HEREAREANUMBER
ACONSTANTLIKEPI9OULLLEARN OFINSTALLERPROGRAMSTHAT
INCHAPTERTHATMARKING LETYOUBUNDLEYOURCLASSES boolean canRecord = false; B
AMETHODASpublic AND WITHAVARIETYOF*6-SSAY FOR
class DVDPlayer {
static MAKESITBEHAVEMUCH DIFFERENTPLATFORMS ANDPUTITALL
LIKEA@GLOBAL!NYCODE INANY ONA#$ 2/-4HENTHEEND USER BULLET POINTS void playTape() {
CLASSOFYOURAPPLICATION CAN CANINSTALLTHECORRECTVERSIONOF System.out.println(“tape playing”); boolean canRecord = false;
THE*6-ASSUMINGTHEYDONT
ß Object-oriented programming lets you extend
ACCESSAPUBLICSTATICMETHOD
a program without having to touch previously- }
!NDIFYOUMARKAVARIABLEAS ALREADYHAVEITONTHEIRMACHINE
public static ANDfinal tested, working code. void recordDVD() {
nYOUHAVEESSENTIALLYMADEA ß All Java code is defined in a class. void recordTape() { System.out.println(“DVD recording”);
GLOBALLY AVAILABLECONSTANT A class describes how to make an object of System.out.println(“tape recording”);
Q: 7HATIF)HAVEAHUNDRED ß }
CLASSES/RATHOUSAND)SNT that class type. A class is like a blueprint. } }
THATABIGPAINTODELIVER ß An object can take care of itself; you don’t }
Q: 4HENHOWISTHISOBJECT ALLTHOSEINDIVIDUALlLES have to know or care how the object does it.
ORIENTEDIFYOUCANSTILLMAKE #AN)BUNDLETHEMINTOONE class DVDPlayerTestDrive {
ß An object knows things and does things.
GLOBALFUNCTIONSANDGLOBAL !PPLICATION4HING class TapeDeckTestDrive { public static void main(String [] args) {
DATA ß Things an object knows about itself are called
public static void main(String [] args) {
instance variables. They represent the state
A: 9ES ITWOULDBEABIG of an object. DVDPlayer d = new DVDPlayer();
A: &IRSTOFALL EVERYTHING PAINTODELIVERAHUGEBUNCHOF ß Things an object does are called methods. t.canRecord = true; d.canRecord = true;
IN*AVAGOESINACLASS3OTHE INDIVIDUALFILESTOYOUREND USERS They represent the behavior of an object. t.playTape(); d.playDVD();
CONSTANTFORPIANDTHEMETHOD BUTYOUWONTHAVETO9OUCAN
FORrandom() ALTHOUGHBOTH PUTALLOFYOURAPPLICATIONFILES ß When you create a class, you may also want
PUBLICANDSTATIC AREDEFINED INTOA*AVA!RCHIVEnAJARFILEn to create a separate test class which you’ll if (t.canRecord == true) { if (d.canRecord == true) {
WITHINTHEMathCLASS!NDYOU THATSBASEDONTHEPKZIPFORMAT use to create objects of your new class type. t.recordTape(); d.recordDVD();
MUSTKEEPINMINDTHATTHESE )NTHEJARFILE YOUCANINCLUDE ß A class can inherit instance variables and
STATICGLOBAL LIKE THINGSARETHE ASIMPLETEXTFILEFORMATTEDAS } }
methods from a more abstract superclass.
EXCEPTIONRATHERTHANTHERULE SOMETHINGCALLEDAMANIFEST THAT
IN*AVA4HEYREPRESENTAVERY DEFINESWHICHCLASSINTHATJAR ß At runtime, a Java program is nothing more } }
SPECIALCASE WHEREYOUDONT HOLDSTHEMAIN METHODTHAT than objects ‘talking’ to other objects.
} }
HAVEMULTIPLEINSTANCESOBJECTS SHOULDRUN

you are here4 41 42 chapter 2


classes and objects puzzle: Pool Puzzle

public class EchoTestDrive {


Code Magnets public static void main(String [] args) {
1dQ^OU_Q Echo e1 = new Echo();
!*AVAPROGRAMISALLSCRAMBLEDUPON
THEFRIDGE#ANYOURECONSTRUCTTHE _________________________
CODESNIPPETSTOMAKEAWORKING*AVA Pool Puzzle int x = 0;
PROGRAMTHATPRODUCESTHEOUTPUTLISTED d.playSnare();
9OURJOBISTOTAKECODESNIPPETSFROM while ( ___________ ) {
BELOW3OMEOFTHECURLYBRACESFELLON THEPOOLANDPLACETHEMINTOTHE
THEFLOORANDTHEYWERETOOSMALLTOPICK DrumKit d = new DrumKit(); BLANKLINESINTHECODE9OUMAY e1.hello();
UP SOFEELFREETOADDASMANYOFTHOSE USETHESAMESNIPPETMORETHAN __________________________
ASYOUNEED ONCE ANDYOUWONTNEEDTOUSE
= true; if ( ____________ ) {
boolean topHat ALLTHESNIPPETS9OURGOALISTO
re = true; MAKECLASSESTHATWILLCOMPILEAND e2.count = e2.count + 1;
boolean sna RUNANDPRODUCETHEOUTPUTLISTED }
if ( ____________ ) {
void playSnare() { /UTPUT e2.count = e2.count + e1.count;
g”); File Edit Window Help Implode }
System.out.println(“bang bang ba-ban
%java EchoTestDrive x = x + 1;
}
helloooo... }
helloooo... System.out.println(e2.count);
public static void main(String [] args) { helloooo... }
helloooo... }

10
class ____________ {
if (d.s int _________ = 0;
nare == true
) {
d.playSn void ___________ {
are(); "ONUS1UESTION
} System.out.println(“helloooo... “);
)FTHELASTLINEOFOUTPUTWAS }
INSTEADOFHOWWOULD }
YOUCOMPLETETHEPUZZLE
d.snare = false;
.OTE%ACHSNIPPET
class DrumKitTestDrive { FROMTHEPOOLCANBE
USEDMORETHANONCE
X X
();
TopHat Y X %CHO
d.play
E X 4ESTER
class DrumKit { ECHO
COUNT X EE
EE  COUNT %CHOE
ECOUNT  HELLO %CHOEE
void playTopH
at () { %CHOENEW%CHO  X
ECOUNTCOUNT 
System.out.p X
rintln(“ding ECOUNTECOUNT 
File Edit Window Help Dance
ding da-ding”
} );
% java DrumKitTestDrive
bang bang ba-bang
ding ding da-ding

you are here4 43 44 chapter 2


classes and objects exercise solutions

Be the Compiler:
!BUNCHOF*AVACOMPONENTS INFULLCOSTUME AREPLAYINGAPARTY
GAME h7HOAM)v4HEYGIVEYOUACLUE ANDYOUTRYTOGUESSWHO 1dQ^OU_Q class TapeDeck {
THEYARE BASEDONWHATTHEYSAY!SSUMETHEYALWAYSTELLTHETRUTH boolean canRecord = false;
ABOUTTHEMSELVES)FTHEYHAPPENTOSAYSOMETHINGTHATCOULDBETRUE %XERCISE3OLUTIONS void playTape() {
FORMORETHANONEOFTHEM CHOOSEALLFORWHOMTHATSENTENCECAN
APPLY&ILLINTHEBLANKSNEXTTOTHESENTENCEWITHTHENAMESOFONEOR
System.out.println(“tape playing”);
MOREATTENDEES4HEFIRSTONESONUS A }
void recordTape() {
I?
am 4ONIGHTSATTENDEES
System.out.println(“tape recording”);
Who #LASS-ETHOD/BJECT)NSTANCEVARIABLE }
}

Code Magnets: class TapeDeckTestDrive {


I am compiled from a .java file. class public static void main(String [] args) {
class DrumKit {
My instance variable values can TapeDeck t = new TapeDeck( );
be different from my buddy’s boolean topHat = true; t.canRecord = true;
values. boolean snare = true; t.playTape();

void playTopHat() { if (t.canRecord == true) {


I behave like a template.
System.out.println(“ding ding da-ding”); t.recordTape();
} }
I like to do stuff.
} We’ve got the template, now we have
void playSnare() { } to make an object !
I can have many methods. System.out.println(“bang bang ba-bang”);
}
I represent ‘state’. }
class DVDPlayer {
boolean canRecord = false;
I have behaviors. class DrumKitTestDrive {
void recordDVD() {
public static void main(String [] args) {
System.out.println(“DVD recording”);
I am located in objects. }
DrumKit d = new DrumKit();
void playDVD ( ) {
d.playSnare();
I live on the heap. System.out.println(“DVD playing”);
d.snare = false;
}
d.playTopHat();
I am used to create object instances. }
if (d.snare == true) {
My state can change. class DVDPlayerTestDrive {
d.playSnare();
public static void main(String [] args) {
}
DVDPlayer d = new DVDPlayer();
I declare methods. }
d.canRecord = true;
} B
d.playDVD();
I can change at runtime. if (d.canRecord == true) {
File Edit Window Help Dance
d.recordDVD();
% java DrumKitTestDrive
}
bang bang ba-bang
} The line: d.playDVD( ); wouldn’t
ding ding da-ding
} compile without a method !

you are here4 45 46 chapter 2


classes and objects

0UZZLE3OLUTIONS

Pool Puzzle
public class EchoTestDrive {
public static void main(String [] args) { 7HOAM)
Echo e1 = new Echo();
Echo e2 = new Echo( ); // the correct answer I am compiled from a .java file. class
- or - My instance variable values can be
Echo e2 = e1; // is the bonus answer! different from my buddy’s values. object
int x = 0;
while ( x < 4 ) {
I behave like a template. class
e1.hello(); I like to do stuff. object, method
e1.count = e1.count + 1;
if ( x == 3 ) {
I can have many methods. class, object
e2.count = e2.count + 1; I represent ‘state’. instance variable
}
if ( x > 0 ) {
I have behaviors. object, class
e2.count = e2.count + e1.count; I am located in objects. method, instance variable
}
x = x + 1; I live on the heap. object
} I am used to create object
System.out.println(e2.count); instances. class
}
} My state can change. object, instance variable
I declare methods. class
class Echo {
int count = 0; I can change at runtime. object, instance variable
void hello( ) {
System.out.println(“helloooo... “); Note: both classes and objects are said to have state and behavior.
} They’re defined in the class, but the object is also said to ‘have’
} them. Right now, we don’t care where they technically live.

File Edit Window Help Assimilate


%java EchoTestDrive
helloooo...
helloooo...
helloooo...
helloooo...
10

you are here4 47


8 interfaces and abstract classes

Serious Polymorphism

Inheritance is just the beginning. 4OEXPLOITPOLYMORPHISM WENEEDINTERFACES


ANDNOTTHE'5)KIND 7ENEEDTOGOBEYONDSIMPLEINHERITANCETOALEVELOFFLEXIBILITYAND
EXTENSIBILITYYOUCANGETONLYBYDESIGNINGANDCODINGTOINTERFACESPECIFICATIONS3OMEOFTHE
COOLESTPARTSOF*AVAWOULDNTEVENBEPOSSIBLEWITHOUTINTERFACES SOEVENIFYOUDONTDESIGN
WITHTHEMYOURSELF YOUSTILLHAVETOUSETHEM"UTYOULLWANTTODESIGNWITHTHEM9OULLNEED
TODESIGNWITHTHEM9OULLWONDERHOWYOUEVERLIVEDWITHOUTTHEM7HATSANINTERFACE)TS
AABSTRACTCLASS7HATSANABSTRACTCLASS)TSACLASSTHATCANTBEINSTANTIATED7HATSTHAT
GOODFOR9OULLSEEINJUSTAFEWMOMENTS"UTIFYOUTHINKABOUTTHEENDOFTHELASTCHAPTER
ANDHOWWEUSEDPOLYMORPHICARGUMENTSSOTHATASINGLE6ETMETHODCOULDTAKE!NIMAL
SUBCLASSESOFALLTYPES WELL THATWASJUSTSCRATCHINGTHESURFACE)NTERFACESARETHEPOLYIN
POLYMORPHISM4HEABINABSTRACT4HECAFFEINEIN*AVA

this is a new chapter 197


designing with inheritance interfaces and polymorphism

Did we forget about something We know we can say:

when we designed this? Wolf aWolf = new Wolf();


Animal
4HECLASSSTRUCTUREISNTTOOBAD7EVEDESIGNED
picture
ITSOTHATDUPLICATECODEISKEPTTOAMINIMUM
food
ANDWEVEOVERRIDDENTHEMETHODSTHATWETHINK hunger aWolf
SHOULDHAVESUBCLASS SPECIlCIMPLEMENTATIONS boundaries
A Wolf reference to a W
7EVEMADEITNICEANDmEXIBLEFROMA location olf object
POLYMORPHICPERSPECTIVE BECAUSEWECANDESIGN Wolf object. Wolf
!NIMAL USINGPROGRAMSWITH!NIMALARGUMENTS makeNoise()
eat()
These two are the same type.
ANDARRAYDECLARATIONS SOTHATANY!NIMAL
SUBTYPEˆINCLUDINGTHOSEWENEVERIMAGINEDATTHE sleep()
TIMEWEWROTEOURCODEˆCANBEPASSEDINANDUSED roam()
ATRUNTIME7EVEPUTTHECOMMONPROTOCOLFOR
ALL!NIMALSTHEFOURMETHODSTHATWEWANTTHE
WORLDTOKNOWALL!NIMALSHAVE INTHE!NIMAL And we know we can say:
SUPERCLASS ANDWEREREADYTOSTARTMAKINGNEW Animal aHippo = new Hippo();
,IONSAND4IGERSAND(IPPOS
Feline

Canine aHippo
Animal reference to Hi t
a Hippo object. ppo
objec
roam()
Animal
Hippo
roam()
These two are NOT the same type.
size
picture
food
makeNoise()
prey
eat()

Lion
size
picture
food
makeNoise()
But here’s where it gets weird:
prey
eat() Animal anim = new Animal();
Dog

Cat size
picture
size food anim
Tiger makeNoise() Animal reference to
?
picture Wolf prey
size food eat() an Animal object. An
makeNoise() imal bject
picture prey size o
eat() Animal
food picture
makeNoise()
prey food
makeNoise()
eat() These two are the same type, but...
prey
eat()
what the heck does an Animal object look like?

198 chapter 8 you are here4 199


when objects go bad interfaces and polymorphism

What does a new Animal() object The compiler won’t let you instantiate
look like? an abstract class
!NABSTRACTCLASSMEANSTHATNOBODYCANEVERMAKEANEW
INSTANCEOFTHATCLASS9OUCANSTILLUSETHATABSTRACTCLASSASA
DECLAREDREFERENCETYPE FORTHEPURPOSEOFPOLYMORPHISM BUT
YOUDONTHAVETOWORRYABOUTSOMEBODYMAKINGOBJECTSOFTHAT
TYPE4HECOMPILERGUARANTEESIT

abstract public class Canine extends Animal


{

scary objects public void roam() { }


}
public class MakeCanine {
ways assign
public void go() { OK , be ca us e you can al ss reference,
la
This is perc
Canine c;
ject to a su
What are the instance variable values? a subclass obsuperclass is abstract.
c = new Dog(); even if the
Some classes just should not be
c = new Canine();
instantiated! class Canine
c.roam();
)TMAKESSENSETOCREATEA7OLFOBJECTORA(IPPO 9OUCANSTILLUSETHATABSTRACTTYPEASAREFERENCETYPE
so the compi is marked abstract,
ler will NOT
OBJECTORA4IGEROBJECT BUTWHATEXACTLYISAN )NFACT THATSABIGPARTOFWHYYOUHAVETHATABSTRACT } let you do th
!NIMALOBJECT7HATSHAPEISIT7HATCOLOR SIZE CLASSINTHElRSTPLACETOUSEITASAPOLYMORPHIC
is.
}
NUMBEROFLEGS ARGUMENTORRETURNTYPE ORTOMAKEAPOLYMORPHIC
File Edit Window Help BeamMeUp
4RYINGTOCREATEANOBJECTOFTYPE!NIMALISLIKEA ARRAY 
NIGHTMARE3TAR4REK©TRANSPORTERACCIDENT4HE 7HENYOUREDESIGNINGYOURCLASSINHERITANCE % javac MakeCanine.java
ONEWHERESOMEWHEREINTHEBEAM ME UPPROCESS STRUCTURE YOUHAVETODECIDEWHICHCLASSESARE
MakeCanine.java:5: Canine is abstract;
SOMETHINGBADHAPPENEDTOTHEBUFFER ABSTRACTANDWHICHARECONCRETE#ONCRETECLASSESARE
cannot be instantiated
"UTHOWDOWEDEALWITHTHIS7ENEEDAN!NIMAL THOSETHATARESPECIlCENOUGHTOBEINSTANTIATED!
CONCRETECLASSJUSTMEANSTHATITS/+TOMAKEOBJECTS c = new Canine();
CLASS FORINHERITANCEANDPOLYMORPHISM"UTWE ^
WANTPROGRAMMERSTOINSTANTIATEONLYTHELESS OFTHATTYPE
1 error
ABSTRACTSUBCLASSESOFCLASS!NIMAL NOT!NIMALITSELF -AKINGACLASSABSTRACTISEASYˆPUTTHEKEYWORD
7EWANT4IGEROBJECTSAND,IONOBJECTS NOT!NIMAL abstractBEFORETHECLASSDECLARATION
OBJECTS
An abstract class has virtually* no use, no value, no
&ORTUNATELY THERESASIMPLEWAYTOPREVENTACLASS abstract class Canine extends Animal { purpose in life, unless it is extended.
FROMEVERBEINGINSTANTIATED)NOTHERWORDS TOSTOP
ANYONEFROMSAYINGhnewvONTHATTYPE"YMARKING public void roam() { }
THECLASSASabstract THECOMPILERWILLSTOPANY
With an abstract class, the guys doing the work at runtime
}
CODE ANYWHERE FROMEVERCREATINGANINSTANCEOF are instances of a subclass of your abstract class.
THATTYPE
*There is an exception to this—an abstract class can
have static members (see chapter 10).
200 chapter 8 you are here4 201
abstract and concrete classes interfaces and polymorphism

Abstract vs. Concrete abstract Abstract methods


!CLASSTHATSNOTABSTRACTISCALLED Animal "ESIDESCLASSES YOUCANMARKMETHODSABSTRACT TOO!NABSTRACT
ACONCRETECLASS)NTHE!NIMAL CLASSMEANSTHECLASSMUSTBEEXTENDEDANABSTRACTMETHODMEANS
INHERITANCETREE IFWEMAKE THEMETHODMUSTBEOVERRIDDEN9OUMIGHTDECIDETHATSOMEORALL
!NIMAL #ANINE AND&ELINE It really sucks to
BEHAVIORSINANABSTRACTCLASSDONTMAKEANYSENSEUNLESSTHEYRE
ABSTRACT THATLEAVES(IPPO 7OLF be an abstract method.
abstract IMPLEMENTEDBYAMORESPECIlCSUBCLASS)NOTHERWORDS YOUCANT
$OG 4IGER ,ION AND#ATASTHE THINKOFANYGENERICMETHODIMPLEMENTATIONTHATCOULDPOSSIBLYBE You don’t have a body.
CONCRETESUBCLASSES Canine
concrete USEFULFORSUBCLASSES7HATWOULDAGENERICEAT METHODLOOKLIKE
&LIPTHROUGHTHE*AVA!0)AND Hippo
An abstract method has no body!
YOULLlNDALOTOFABSTRACTCLASSES abstract
ESPECIALLYINTHE'5)LIBRARY7HAT "ECAUSEYOUVEALREADYDECIDEDTHEREISNTANYCODETHATWOULDMAKE
Feline
DOESA'5)#OMPONENTLOOK concrete SENSEINTHEABSTRACTMETHOD YOUWONTPUTINAMETHODBODY3ONO
LIKE4HE#OMPONENTCLASSISTHE Dog CURLYBRACESˆJUSTENDTHEDECLARATIONWITHASEMICOLON
SUPERCLASSOF'5) RELATEDCLASSES
FORTHINGSLIKEBUTTONS TEXTAREAS concrete public abstract void eat();
SCROLLBARS DIALOGBOXES YOUNAME concrete
Cat
IT9OUDONTMAKEANINSTANCEOF Wolf
!
AGENERIC#OMPONENTANDPUTITON concrete concrete No method boadysemicolon.
THESCREEN YOUMAKEA*"UTTON)N Lion End it with
OTHERWORDS YOUINSTANTIATEONLYA Tiger
CONCRETESUBCLASSOF#OMPONENT BUT
If you declare an abstract method, you MUST
NEVER#OMPONENTITSELF
mark the class abstract as well. You can’t have
an abstract method in a non-abstract class.
YiX`e )FYOUPUTEVENASINGLEABSTRACTMETHODINACLASS YOUHAVETO
gfn\i abstract or concrete? MAKETHECLASSABSTRACT"UTYOUCANMIXBOTHABSTRACTANDNON
(OWDOYOUKNOWWHENACLASSSHOULDBE ABSTRACTMETHODSINTHEABSTRACTCLASS
ABSTRACT7INEISPROBABLYABSTRACT"UTWHAT
Hmmmm... do I Hmmmm... the Camelot ABOUT2EDAND7HITE!GAINPROBABLYABSTRACT there are no
feel like red or Vineyards 1997 Pinot
white tonight? Noir was a pretty
FORSOMEOFUS ANYWAY "UTATWHATPOINTINTHE
Dumb Questions
decent year... HIERARCHYDOTHINGSBECOMECONCRETE
Q: 7HATISTHEPOINTOFANABSTRACTMETHOD)THOUGHT Q: 7HICHISGOODBECAUSE
$OYOUMAKE0INOT.OIRCONCRETE ORISITABSTRACT THEWHOLEPOINTOFANABSTRACTCLASSWASTOHAVECOMMON
TOO)TLOOKSLIKETHE#AMELOT6INEYARDS CODETHATCOULDBEINHERITEDBYSUBCLASSES
0INOT.OIRISPROBABLYCONCRETENOMATTERWHAT A: 0OLYMORPHISM2EMEMBER WHATYOUWANTISTHE
ABILITYTOUSEASUPERCLASSTYPEOFTENABSTRACT ASAMETHOD
"UTHOWDOYOUKNOWFORSURE A: )NHERITABLEMETHODIMPLEMENTATIONSINOTHERWORDS ARGUMENT RETURNTYPE ORARRAYTYPE4HATWAY YOUGETTO
METHODSWITHACTUALBODIES ARE!'OOD4HINGTOPUTINA ADDNEWSUBTYPESLIKEANEW!NIMALSUBCLASS TOYOUR
,OOKATTHE!NIMALINHERITANCETREEABOVE$OTHE
SUPERCLASS7HENITMAKESSENSE!NDINANABSTRACTCLASS IT PROGRAMWITHOUTHAVINGTOREWRITEORADD NEWMETHODS
CHOICESWEVEMADEFORWHICHCLASSESAREABSTRACT OFTENDOESNTMAKESENSE BECAUSEYOUCANTCOMEUPWITH TODEALWITHTHOSENEWTYPES)MAGINEHOWYOUDHAVETO
ANDWHICHARECONCRETESEEMAPPROPRIATE ANYGENERICCODETHATSUBCLASSESWOULDFINDUSEFUL4HE CHANGETHE6ETCLASS IFITDIDNTUSE!NIMALASITSARGUMENT
POINTOFANABSTRACTMETHODISTHATEVENTHOUGHYOUHAVENT TYPEFORMETHODS9OUDHAVETOHAVEASEPARATEMETHOD
7OULDYOUCHANGEANYTHINGABOUTTHE!NIMAL
PUTINANYACTUALMETHODCODE YOUVESTILLDEFINEDPARTOF FOREVERYSINGLE!NIMALSUBCLASS/NETHATTAKESA,ION ONE
INHERITANCETREEOTHERTHANADDINGMORE!NIMALS THEPROTOCOLFORAGROUPOFSUBTYPESSUBCLASSES  THATTAKESA7OLF ONETHATTAKESAYOUGETTHEIDEA3OWITH
OFCOURSE  ANABSTRACTMETHOD YOURESAYING h!LLSUBTYPESOFTHISTYPE
HAVE4()3METHODvFORTHEBENEFITOFPOLYMORPHISM

202 chapter 8 you are here4 203


you must implement abstract methods interfaces and polymorphism

Sharpen your pencil !BSTRACTVS#ONCRETE#LASSES


You MUST implement all abstract methods ,ETSPUTALLTHISABSTRACTRHETORICINTOSOMECONCRETEUSE)NTHEMIDDLE
COLUMNWEVELISTEDSOMECLASSES9OURJOBISTOIMAGINEAPPLICATIONS
WHERETHELISTEDCLASSMIGHTBECONCRETE ANDAPPLICATIONSWHERETHELISTED
I have wonderful news, CLASSMIGHTBEABSTRACT7ETOOKASHOTATTHElRSTFEWTOGETYOUGOING
&OREXAMPLE CLASS4REEWOULDBEABSTRACTINATREENURSERYPROGRAM WHERE
mother. Joe finally implemented
DIFFERENCESBETWEENAN/AKANDAN!SPENMATTER"UTINAGOLFSIMULATION
all his abstract methods! Now PROGRAM 4REEMIGHTBEACONCRETECLASSPERHAPSASUBCLASSOF/BSTACLE
everything is working just the BECAUSETHEPROGRAMDOESNTCAREABOUTORDISTINGUISHBETWEENDIFFERENT
way we planned... TYPESOFTREES4HERESNOONERIGHTANSWERITDEPENDSONYOURDESIGN

#ONCRETE 3AMPLECLASS !BSTRACT

golf course simulation 4REE tree nursery application

???????????????????? (OUSE architect application

satellite photo application 4OWN ?????????????????????

???????????????????? &OOTBALL0LAYER coaching application


Implementing an abstract
method is just like
overriding a method. ???????????????????? #HAIR ?????????????????????

!BSTRACTMETHODSDONTHAVEABODYTHEYEXISTSOLELYFORPOLYMORPHISM4HAT ???????????????????? #USTOMER ?????????????????????


MEANSTHElRSTCONCRETECLASSINTHEINHERITANCETREEMUSTIMPLEMENTALLABSTRACT
METHODS ???????????????????? 3ALES/RDER ?????????????????????
9OUCAN HOWEVER PASSTHEBUCKBYBEINGABSTRACTYOURSELF)FBOTH!NIMALAND
#ANINEAREABSTRACT FOREXAMPLE ANDBOTHHAVEABSTRACTMETHODS CLASS#ANINE
???????????????????? "OOK ?????????????????????
DOESNOTHAVETOIMPLEMENTTHEABSTRACTMETHODSFROM!NIMAL"UTASSOONASWE
GETTOTHElRSTCONCRETESUBCLASS LIKE$OG THATSUBCLASSMUSTIMPLEMENTALLOFTHE
ABSTRACTMETHODSFROMBOTH!NIMALAND#ANINE ???????????????????? 3TORE ?????????????????????
"UTREMEMBERTHATANABSTRACTCLASSCANHAVEBOTHABSTRACTANDNON ABSTRACT
METHODS SO#ANINE FOREXAMPLE COULDIMPLEMENTANABSTRACTMETHODFROM ???????????????????? 3UPPLIER ?????????????????????
!NIMAL SOTHAT$OGDIDNTHAVETO"UTIF#ANINESAYSNOTHINGABOUTTHEABSTRACT
METHODSFROM!NIMAL $OGHASTOIMPLEMENTALLOF!NIMALSABSTRACTMETHODS
???????????????????? 'OLF#LUB ?????????????????????
7HENWESAYhYOUMUSTIMPLEMENTTHEABSTRACTMETHODv THATMEANSYOUMUST
PROVIDEABODY4HATMEANSYOUMUSTCREATEANON ABSTRACTMETHODINYOURCLASS
WITHTHESAMEMETHODSIGNATURENAMEANDARGUMENTS ANDARETURNTYPETHATIS ???????????????????? #ARBURETOR ?????????????????????
COMPATIBLEWITHTHEDECLAREDRETURNTYPEOFTHEABSTRACTMETHOD7HATYOUPUTIN
THATMETHODISUPTOYOU!LL*AVACARESABOUTISTHATTHEMETHODISTHERE INYOUR
???????????????????? /VEN ?????????????????????
CONCRETESUBCLASS

204 chapter 8 you are here4 205


polymorphism examples interfaces and polymorphism

Polymorphism in action Uh-oh, now we need to keep Cats, too.


,ETSSAYTHATWEWANTTOWRITEOUROWNKINDOFLISTCLASS ONETHATWILLHOLD 7EHAVEAFEWOPTIONSHERE
$OGOBJECTS BUTPRETENDFORAMOMENTTHATWEDONTKNOWABOUTTHE  -AKEASEPARATECLASS -Y#AT,IST TOHOLD#ATOBJECTS0RETTYCLUNKY
!RRAY,ISTCLASS&ORTHElRSTPASS WELLGIVEITJUSTANADD METHOD7ELLUSE
ASIMPLE$OGARRAY$OG;= TOKEEPTHEADDED$OGOBJECTS ANDGIVEITA  -AKEASINGLECLASS $OG!ND#AT,IST THATKEEPSTWODIFFERENTARRAYSASINSTANCE
LENGTHOF7HENWEREACHTHELIMITOF$OGOBJECTS YOUCANSTILLCALLTHE VARIABLESANDHASTWODIFFERENTADD METHODSADD#AT#ATC ANDADD$OG$OG
ADD METHODBUTITWONTDOANYTHING)FWERENOTATTHELIMIT THEADD D !NOTHERCLUNKYSOLUTION
METHODPUTSTHE$OGINTHEARRAYATTHENEXTAVAILABLEINDEXPOSITION THEN  -AKEHETEROGENEOUS!NIMAL,ISTCLASS THATTAKESANYKINDOF!NIMALSUBCLASS
INCREMENTSTHATNEXTAVAILABLEINDEXNEXT)NDEX  SINCEWEKNOWTHATIFTHESPECCHANGEDTOADD#ATS SOONERORLATERWELLHAVE
SOMEOTHERKINDOFANIMALADDEDASWELL 7ELIKETHISOPTIONBEST SOLETSCHANGE
OURCLASSTOMAKEITMOREGENERIC TOTAKE!NIMALSINSTEADOFJUST$OGS7EVE
HIGHLIGHTEDTHEKEYCHANGESTHELOGICISTHESAME OFCOURSE BUTTHETYPEHAS
CHANGEDFROM$OGTO!NIMALEVERYWHEREINTHECODE
Building our own Dog-specific list
(Perhaps the world’s worst attempt at making our Building our own Animal-specific list ga
own ArrayList kind of class, from scratch.) e’re not makin
public class MyAnimalList {
Don’t panic.obWject; we’re making a
E RSI O

V
N
d Dog array new Animal ject, of type Animal.
E RSI O

V
N
1 public class MyDogList { Use a plain olscenes. 2 private Animal[] animals = new Animal[5]; new array obyou cannot make a new
behind th e private int nextIndex = 0;
private Dog [] dogs = new Dog[5];
(Remember, an abstract type, but
MyDogList
MyAnimalList instance of ake an array object
private int nextIndex = 0; h public void add(Animal a) {
Dog[] dogs
you CAN m HOLD that type.)
We’ll increment this eaced. if (nextIndex < animals.length) {
int nextIndex Animal[] animals declared to
time a new Dog is add int nextIndex animals[nextIndex] = a;
System.out.println(“Animal added at “ + nextIndex);
add(Dog d) public void add(Dog d) { add(Animal a) nextIndex++;
at the limit
if (nextIndex < dogs.length) { the Dog }
If we’re not alreadyadd
of the dogs array, }
dogs[nextIndex] = d; and print a message. }

System.out.println(“Dog added at “ + nextIndex);


public class AnimalTestDrive{
nextIndex++;
increment, public static void main (String[] args) {
} next index to give us MyAnimalList list = new MyAnimalList();
to use the Dog a = new Dog();
} Cat c = new Cat();
} list.add(a);
list.add(c);
}
}
File Edit Window Help Harm

% java AnimalTestDrive
Animal added at 0
Animal added at 1

206 chapter 8 you are here4 207


the ultimate superclass: Object interfaces and polymorphism

What about non-Animals? Why not make So what’s in this ultra-super-megaclass Object?
a class generic enough to take anything? )FYOUWERE*AVA WHATBEHAVIORWOULDYOUWANTEVERY
OBJECTTOHAVE(MMMMLETSSEEHOWABOUTA Object
9OUKNOWWHERETHISISHEADING7EWANTTOCHANGETHE a few of the METHODTHATLETSYOUlNDOUTIFONEOBJECTISEQUAL
TYPEOFTHEARRAY ALONGWITHTHEADD METHODARGUMENT TO E RSI O
(These are just yList...there
Ar ra TOANOTHEROBJECT7HATABOUTAMETHODTHATCAN boolean equals()

V
N
methods in
SOMETHINGABOVE!NIMAL3OMETHINGEVENMOREGENERIC MORE 3 TELLYOUTHEACTUALCLASSTYPEOFTHATOBJECT-AYBEA Class getClass() the methods
are many more.) METHODTHATGIVESYOUAHASHCODEFORTHEOBJECT SO
ABSTRACTTHAN!NIMAL"UTHOWCANWEDOIT7EDONTHAVEA int hashCode() Just SOME of .
SUPERCLASSFOR!NIMAL YOUCANUSETHEOBJECTINHASHTABLESWELLTALKABOUT of clas s Obje ct
String toString()
*AVASHASHTABLESINCHAPTERANDAPPENDIX" 
4HENAGAIN MAYBEWEDO
!RRAY,IST /H HERESAGOODONEˆAMETHODTHATPRINTSOUTA
2EMEMBERTHOSEMETHODSOF!RRAY,IST 3TRINGMESSAGEFORTHATOBJECT
,OOKHOWTHEREMOVE CONTAINS AND YourClassHere Every class you write inherits all the
INDEX/FMETHODALLUSEANOBJECTOFTYPE LEM !NDWHATDOYOUKNOW!SIFBYMAGIC CLASS/BJECT
/BJECT DOESINDEEDHAVEMETHODSFORTHOSEFOURTHINGS
OVE/BJECTE DEXPARAMETER2ETURNS methods of class Object. The classes
BOOLEANREM JEC TATTHEIN
OB
2EMOVESTHE THELIST 4HATSNOTALL THOUGH BUTTHESEARETHEONESWE
you’ve written inherited methods you
LEMENTWASIN
Every class in Java extends @TRUEIFTHEE REALLYCAREABOUT didn’t even know you had.
class Object. LEM R
AINS/BJECTE CTPARAMETE
1 equals(Object o)
BOOLEANCONT FTHERESAMATCHFORTHEOBJE
2ETURNS@T RU EI
#LASS/BJECTISTHEMOTHEROFALLCLASSESITS 3 hashCode()
THESUPERCLASSOFEVERYTHING PTY Dog a = new Dog();
BOOLEANIS%M ELEMENTS Cat c = new Cat(); Cat c = new Cat();
%VENIFYOUTAKEADVANTAGEOFPOLYMORPHISM FT HELISTHASNO System.out.println(c.hashCode());
2ETURNS@TRUEI
YOUSTILLHAVETOCREATEACLASSWITHMETHODS  if (a.equals(c)) {
BJECTELEM RAMETER OR File Edit Window Help Drop
THATTAKEANDRETURNYOURPOLYMORPHICTYPE INTINDEX/F/ ERTHEINDEXOFTHEOBJECTPA System.out.println(“true”); shcode
7ITHOUTACOMMONSUPERCLASSFOREVERYTHING 2ETURNSEITH } else { % java TestObject Prints out a ha (for
IN*AVA THEREDBENOWAYFORTHEDEVELOPERS NDEX  System.out.println(“false”);
ECTGETINTI IONINTHELIST
/BJ
for the object as a
POSIT } 8202111
OF*AVATOCREATECLASSESWITHMETHODSTHAT EMENTATTHIS now, think of it
2ETURNSTHEEL
COULDTAKEYOURCUSTOMTYPESTYPESTHEYNEVER File Edit Window Help Stop unique ID).
BJECTELEM  
KNEWABOUTWHENTHEYWROTETHE!RRAY,ISTCLASS BO OLEANADD/ TRETURNS@TRUE
ENTTOTHELIS % java TestObject
!DDSTHEELEM
3OYOUWEREMAKINGSUBCLASSESOFCLASS/BJECT Tells you if two objects are
FROMTHEVERYBEGINNINGANDYOUDIDNTEVEN MORE false considered ‘equal’ (we’ll talk
KNOWIT%VERYCLASSYOUWRITEEXTENDS/BJECT about what ‘equal’ really 4 toString()
WITHOUTYOUREVERHAVINGTOSAYIT"UTYOUCAN means in appendix B). Cat c = new Cat();
THINKOFITASTHOUGHACLASSYOUWRITELOOKSLIKE ist methods use the System.out.println(c.toString());
THIS Many of the ArrayL ce File Edit Window Help LapseIntoComa
ic type, Object. Sin
public class Dog extends Object { } ultimate polymorph is a subclass of Object,
va
every class in Ja hing! % java TestObject
"UTWAITAMINUTE $OGALREADYEXTENDSSOMETHING #ANINE thods can take anyt 2 getClass()
4HATS/+4HECOMPILERWILLMAKE#ANINEEXTEND/BJECT these ArrayList me ) Cat c = new Cat(); Cat@7d277f
INSTEAD%XCEPT#ANINEEXTENDS!NIMAL.OPROBLEM THENTHE , the get() and add( System.out.println(c.getClass());
(Note: as of Java 5.0k a little different
COMPILERWILLJUSTMAKE!NIMALEXTEND/BJECT File Edit Window Help Faint
methods actually loo here, but for now this ring message
Any class that doesn’t explicitly extend another than the ones shown about it. We’ll get into % java TestObject Gives you back the
Prints out a Stof the class
class, implicitly extends Object. with the name number we
is the way to thinktle later.) class that object was
3O SINCE$OGEXTENDS#ANINE ITDOESNTDIRECTLYEXTEND/BJECT class Cat and some other t.
the full story a lit instantiated from.
ALTHOUGHITDOESEXTENDITINDIRECTLY ANDTHESAMEISTRUE rarely care abou
FOR#ANINE BUT!NIMALDOESDIRECTLYEXTEND/BJECT
208 chapter 8 you are here4 209
Object and abstract classes interfaces and polymorphism

there are no
Dumb Questions Q: /+ BACKTOCLASS/BJECT Q: )FITSSOGOODTOUSE Using polymorphic references of type Object has a price...
BEINGNON ABSTRACTSO)GUESS POLYMORPHICTYPES WHY
Q: )SCLASS/BJECTABSTRACT THATMEANSITSCONCRETE (/7 DONTYOUJUSTMAKE!,,YOUR "EFOREYOURUNOFFANDSTARTUSINGTYPE/BJECTFORALLYOURULTRA mEXIBLEARGUMENTANDRETURN
CANYOULETSOMEBODYMAKEAN METHODSTAKEANDRETURNTYPE TYPES YOUNEEDTOCONSIDERALITTLEISSUEOFUSINGTYPE/BJECTASAREFERENCE!NDKEEPINMIND
/BJECTOBJECT)SNTTHATJUST /BJECT THATWERENOTTALKINGABOUTMAKINGINSTANCESOFTYPE/BJECTWERETALKINGABOUTMAKING
A: .O7ELL NOTINTHEFORMAL ASWEIRDASMAKINGAN!NIMAL
*AVASENSEANYWAY/BJECTISA INSTANCESOFSOMEOTHERTYPE BUTUSINGAREFERENCEOFTYPE/BJECT
NON ABSTRACTCLASSBECAUSEITS OBJECT
A: !HHHHTHINKABOUTWHAT 7HENYOUPUTANOBJECTINTOAN!RRAY,IST$OG ITGOESINASA$OG ANDCOMESOUTASA$OG
GOTMETHODIMPLEMENTATION WOULDHAPPEN&ORONETHING
CODETHATALLCLASSESCANINHERIT A: 'OODQUESTION7HYIS YOUWOULDDEFEATTHEWHOLE Make an ArrayList declared
ANDUSEOUT OF THE BOX WITHOUT ITACCEPTABLETOMAKEANEW POINTOF@TYPE SAFETY ONE ArrayList<Dog> myDogArrayList = new ArrayList<Dog>();
to hold Dog objects.
HAVINGTOOVERRIDETHEMETHODS /BJECTINSTANCE"ECAUSE OF*AVASGREATESTPROTECTION Dog aDog = new Dog(); Make a Dog.
SOMETIMESYOUJUSTWANTA MECHANISMSFORYOURCODE7ITH
TYPE SAFETY *AVAGUARANTEESTHAT myDogArrayList.add(aDog); Add the Dog to the list. able.
GENERICOBJECTTOUSEAS WELL AS to a new Dog reference vari
Q: 4HENCANYOUOVERRIDE ANOBJECT!LIGHTWEIGHTOBJECT YOUWONTASKTHEWRONGOBJECT Dog d = myDogArrayList.get(0);
Assign the Dog from the listget() method declares a Dog return
the
THEMETHODSIN/BJECT "YFAR THEMOSTCOMMONUSEOF TODOSOMETHINGYOUMEANTTO (Think of it as though ist<Dog>.)
ANINSTANCEOFTYPE/BJECTISFOR ASKOFANOTHEROBJECTTYPE,IKE type because you used ArrayL
THREADSYNCHRONIZATIONWHICH ASKA&ERRARIWHICHYOUTHINKISA "UTWHATHAPPENSWHENYOUDECLAREITAS!RRAY,IST/BJECT)FYOUWANTTOMAKEAN!RRAY,IST
A: 3OMEOFTHEM"UTSOMEOF YOULLLEARNABOUTINCHAPTER  4OASTER TOCOOKITSELF THATWILLLITERALLYTAKEANYKINDOF/BJECT YOUDECLAREITLIKETHIS
THEMAREMARKEDfinal WHICH &ORNOW JUSTSTICKTHATONTHE "UTTHETRUTHIS YOUDONTHAVE
MEANSYOUCANTOVERRIDETHEM BACKBURNERANDASSUMETHAT TOWORRYABOUTTHATFIERY&ERRARI Make an ArrayList declared
9OUREENCOURAGEDSTRONGLY TO YOUWILLRARELYMAKEOBJECTSOF SCENARIO EVENIFYOUDOUSE ArrayList<Object> myDogArrayList = new ArrayList<Object>();
to hold any type of Object.
OVERRIDEHASH#ODE EQUALS TYPE/BJECT EVENTHOUGHYOU /BJECTREFERENCESFOREVERYTHING Dog aDog = new Dog();
ANDTO3TRING INYOUROWN "ECAUSEWHENOBJECTSARE
Make a Dog. (These two steps are the same.)
CAN
CLASSES ANDYOULLLEARNHOWTO REFERREDTOBYAN/BJECT myDogArrayList.add(aDog); Add the Dog to the list.
DOTHATALITTLELATERINTHEBOOK REFERENCETYPE *AVATHINKSITS
"UTSOMEOFTHEMETHODS LIKE Q: 3OISITFAIRTOSAYTHATTHE REFERRINGTOANINSTANCEOFTYPE "UTWHATHAPPENSWHENYOUTRYTOGETTHE$OGOBJECTANDASSIGNITTOA$OGREFERENCE
GET#LASS DOTHINGSTHATMUST MAINPURPOSEFORTYPE/BJECT /BJECT!NDTHATMEANSTHE
WORKINASPECIFIC GUARANTEED ISSOTHATYOUCANUSEITFORA ONLYMETHODSYOUREALLOWEDTO NO!! Won’t compile!! When you use ArrayList<Object>, the get() method
myD
m
Dog d = myDogArrayList.get(0);
WAY POLYMORPHICARGUMENTAND CALLONTHATOBJECTARETHEONES returns type Object. The Compiler knows only that the object inherits from
RETURNTYPE,IKEIN!RRAY,IST DECLAREDINCLASS/BJECT3OIF Object (somewhere in its inheritance tree) but it doesn’t know it’s a Dog !!
YOUWERETOSAY
Q: )F!RRAY,ISTMETHODSARE %VERYTHINGCOMESOUTOFAN!RRAY,IST/BJECTASAREFERENCEOFTYPE/BJECT REGARDLESSOFWHATTHE
GENERICENOUGHTOUSE/BJECT A: 4HE/BJECTCLASSSERVES Object o = new Ferrari(); ACTUALOBJECTIS ORWHATTHEREFERENCETYPEWASWHENYOUADDEDTHEOBJECTTOTHELIST
THENWHATDOESITMEANTOSAY TWOMAINPURPOSESTOACTASA o.goFast(); //Not legal!
!RRAY,IST$OT#OM)THOUGHT POLYMORPHICTYPEFORMETHODS
)WASRESTRICTINGTHE!RRAY,ISTTO THATNEEDTOWORKONANYCLASS 9OUWOULDNTEVENMAKEITPAST
HOLDONLY$OT#OMOBJECTS THATYOUORANYONEELSEMAKES THECOMPILER The objects go IN
ANDTOPROVIDEREALMETHODCODE Objects come out of
as SoccerBall,
THATALLOBJECTSIN*AVANEEDAT "ECAUSE*AVAISASTRONGLY TYPED
A: 9OUWERERESTRICTINGIT RUNTIMEANDPUTTINGTHEMIN Fish, Guitar, and an ArrayList<Object>
LANGUAGE THECOMPILERCHECKS
0RIORTO*AVA !RRAY,ISTS CLASS/BJECTMEANSALLOTHER Car. acting like they’re
TOMAKESURETHATYOURECALLING
COULDNTBERESTRICTED4HEY CLASSESINHERITTHEM 3OMEOF generic instances
AMETHODONANOBJECTTHATS
WEREALLESSENTIALLYWHATYOU THEMOSTIMPORTANTMETHODSIN ACTUALLYCAPABLEOFRESPONDING of class Object. The
GETIN*AVATODAYIFYOUWRITE /BJECTARERELATEDTOTHREADS )NOTHERWORDS YOUCANCALLA ArrayList<Object> Compiler cannot
!RRAY,IST/BJECT)NOTHER ANDWELLSEETHOSELATERINTHE METHODONANOBJECTREFERENCE assume the object
WORDS AN!RRAY,ISTRESTRICTED BOOK ONLYIFTHECLASSOFTHEREFERENCE But they come
TOANYTHINGTHATSAN/BJECT that comes out is of
TYPEACTUALLYHASTHEMETHOD
WHICHMEANSANYOBJECTIN*AVA OUT as though any type other than
7ELLCOVERTHISINMUCHGREATER
INSTANTIATEDFROMANYCLASSTYPE they were of type
DETAILALITTLELATER SODONTWORRY Object.
7ELLCOVERTHEDETAILSOFTHISNEW
IFTHEPICTUREISNTCRYSTALCLEAR Object. Object Object Object Object
TYPESYNTAXLATERINTHEBOOK

210 chapter 8 you are here4 211


When a Dog loses its Dogness interfaces and polymorphism

When a Dog won’t act like a Dog I don’t know what you’re Objects don’t bark.
talking about. Sit? Stay?
4HEPROBLEMWITHHAVINGEVERYTHINGTREATED bark? Hmmmm... I don’t 3ONOWWEKNOWTHATWHENANOBJECTIS
POLYMORPHICALLYASAN/BJECTISTHATTHEOBJECTS recall knowing those. REFERENCEDBYAVARIABLEDECLAREDASTYPE
APPEARTOLOSEBUTNOTPERMANENTLY THEIR /BJECT ITCANTBEASSIGNEDTOAVARIABLE
TRUEESSENCE4HE$OGAPPEARSTOLOSEITSDOGNESS
o
DECLAREDWITHTHEACTUALOBJECTSTYPE
,ETSSEEWHATHAPPENSWHENWEPASSA$OGTO t
!NDWEKNOWTHATTHISCANHAPPENWHEN D og
objec
Object
AMETHODTHATRETURNSAREFERENCETOTHESAME ARETURNTYPEORARGUMENTISDECLARED
$OGOBJECT BUTDECLARESTHERETURNTYPEASTYPE ASTYPE/BJECT ASWOULDBETHECASE
/BJECTRATHERTHAN$OG FOREXAMPLE WHENTHEOBJECTISPUT When you get an object reference from
INTOAN!RRAY,ISTOFTYPE/BJECTUSING
!RRAY,IST/BJECT"UTWHATARETHE
an ArrayList<Object> (or any method
IMPLICATIONSOFTHIS)SITAPROBLEMTO that declares Object as the return type),
method HAVETOUSEAN/BJECTREFERENCEVARIABLE it comes back as a polymorphic reference
public void go() { though the e TOREFERTOA$OGOBJECT,ETSTRYTOCALL type of Object. So you have an Object
lin e w on ’t work! Eventhe very same Dog tht
to bj ec $OGMETHODSONOUR$OG 4HAT #OMPILER
Dog aDog = new Dog(); This ref er en ce rn ty pe O reference to (in this case) a Dog instance.
BAD Dog sameDog g
g = getObject(aDog);
returned 4HINKS )S !N /BJECT
returned areferred to, the retu u assign the
L } argument compiler won’t let bjyoect. a
means the to anything but O Object o = al.get(index); bject has
T hi s is f in e. Class O so you can call
reference ) method, in Java.
public Object getObject(Object o) {
as a int i = o.hashCode(); hashCode(hod on ANY object
return o; nce to the same Dog, but t ha t m et
} We’re returning a refereThis part is perfectly legal. Note:
. o.bark();
o.ba
o.b
return type of Object get() method works when you have Won’t compile! Can’t do this!! The Object class has no idea what
this is similar to how the her than an ArrayList<Dog>. it means to bark(). Even though YOU know it’s
an ArrayList<Object> rat really a Dog at that index, the compiler doesn’t..
File Edit Window Help Remember

DogPolyTest.java:10: incompatible types


The compiler doesn’t know that the
found : java.lang.Object
thing returned from the method is hashCode
()
The compiler decides whether
actually a Dog, so it won’t let you you can call a method based
required: Dog
assign it to a Dog reference. (You’ll on the reference type, not the
Dog sameDog = takeObjects(aDog);
see why on the next page.) actual object type. o
1 error ^
D og t
objec
%VENIFYOUKNOWTHEOBJECTISCAPABLE Object
hBUTITREALLYISA$OG HONESTv THE
COMPILERSEESITONLYASAGENERIC/BJECT Object
The method you’re calling on a
&ORALLTHECOMPILERKNOWS YOUPUTA equals() reference MUST be in the class of
public void go() { This works (although it may not be very "UTTONOBJECTOUTTHERE/RA-ICROWAVE getClass()
Dog aDog = new Dog();
that reference type. Doesn’t matter
useful, as you’ll see in a moment) because you OBJECT/RSOMEOTHERTHINGTHATREALLY hashCode() what the actual object is.
GOOD Object sameDog = getObject(aDog); can assign ANYTHING to a reference of type DOESNTKNOWHOWTOBARK toString()
J } Object, since every class passes the IS-A test 4HECOMPILERCHECKSTHECLASSOFTHE
REFERENCETYPEˆNOTTHEOBJECTTYPEˆTO o.hashCode();
for Object. Every object in Java is an instance
public Object getObject(Object o) { SEEIFYOUCANCALLAMETHODUSINGTHAT
of type Object, because every class in Java has
REFERENCE
The “o” reference was declared as type
return o; Object at the top of its inheritance tree. Object, so you can call methods only if
those methods are in class Object..
}
212 chapter 8 you are here4 213
objects are Objects interfaces and polymorphism

He treats me like an
Object. But I can do so
‘Polymorphism’ means When you put
much more...if only he’d see
‘many forms’. an object in an
me for what I really am. You can treat a Snowboard as a ArrayList<Object>, you
Snowboard or as an Object. can treat it only as an
)FAREFERENCEISLIKEAREMOTECONTROL THE
Object, regardless of
REMOTECONTROLTAKESONMOREANDMOREBUTTONS the type it was when
ASYOUMOVEDOWNTHEINHERITANCETREE! you put it in.
REMOTECONTROLREFERENCE OFTYPE/BJECTHAS
ONLYAFEWBUTTONSˆTHEBUTTONSFORTHEEXPOSED When you get a
METHODSOFCLASS/BJECT"UTAREMOTECONTROL reference from an
OFTYPE3NOWBOARDINCLUDESALLTHEBUTTONSFROM ArrayList<Object>, the
Get in touch with your inner Object. CLASS/BJECT PLUSANYNEWBUTTONSFORNEW reference is always of
METHODS OFCLASS3NOWBOARD4HEMORESPECIlC
!NOBJECTCONTAINSEVERYTHINGITINHERITSFROMEACHOFITS type Object.
THECLASS THEMOREBUTTONSITMAYHAVE
SUPERCLASSES4HATMEANSEVERYOBJECTˆREGARDLESSOFITS
ACTUALCLASSTYPEˆISALSOANINSTANCEOFCLASS/BJECT4HAT /FCOURSETHATSNOTALWAYSTRUEASUBCLASSMIGHT That means you get an
MEANSANYOBJECTIN*AVACANBETREATEDNOTJUSTASA$OG NOTADDANYNEWMETHODS BUTSIMPLYOVERRIDE Object remote control.
"UTTON OR3NOWBOARD BUTALSOASAN/BJECT7HENYOU THEMETHODSOFITSSUPERCLASS4HEKEYPOINTIS
SAYnew Snowboard() YOUGETASINGLEOBJECTONTHE THATEVENIFTHEOBJECTISOFTYPE3NOWBOARD AN
HEAPˆA3NOWBOARDOBJECTˆBUTTHAT3NOWBOARDWRAPS /BJECTREFERENCETOTHE3NOWBOARDOBJECTCANTSEE
ITSELFAROUNDANINNERCOREREPRESENTINGTHE/BJECT THE3NOWBOARD SPECIlCMETHODS
CAPITALh/v PORTIONOFITSELF

Object
)
equals() A single object d( turn
re

Snowboard s = new Snowboard(); ()


sh

getClass() on the heap. g ()


has
h
t

hashCode() Object o = s; rin


Co

)
t oS

toString() d( turn

re
de(

()
)

h Object

sh
g() ash
equ

t
rin
()

Co
al

s
s
()

s(

t oS
)
ge

la

de(
)
rol

getC
tA

Object
nt

Snowboard
ir

Snowboard inherits methods () o

equ
()
loseC
s

al
s

s
()
equals() from superclass Object, and s(
) a

get
et Cl

rol
getClass() g Snowboard

Ai
nt
adds four more.

r
hashCode()
() o
loseC The Snowboard remote control Sn je ct
toString() fewer methods here... ow b
(reference) has more buttons than oard ob
Snowboard
turn() an Object remote control. The o
shred()
Sn
ow b je ct
oard ob Snowboard remote can see the full
getAir() The Object reference can see only the
loseControl()
Snowboardness of the Snowboard
object. It can access all the methods Object parts of the Snowboard object.
There is only ONE object on the heap here. A Snowboard It can access only the methods of class
object. But it contains both the Snowboard class parts of in Snowboard, including both the
inherited Object methods and the Object. It has fewer buttons than the
itself and the Object class parts of itself. Snowboard remote control.
methods from class Snowboard.
214 chapter 8 you are here4 215
casting objects interfaces and polymorphism

So now you’ve seen how much Java


Wait a minute... what good
is a Dog if it comes out of an
cares about the methods in the
ArrayList<Object> and it can’t do Casting an object reference class of the reference variable.
any Dog things? There’s gotta be a back to its real type. You can call a method on an object only if
way to get the Dog back to a state the class of the reference variable has that
of Dogness... method.
Think of the public methods in your class as
your contract, your promise to the outside
o world about the things you can do.
D og t
objec
Object
I hope it doesn’t hurt. 7HENYOUWRITEACLASS YOUALMOSTALWAYSEXPOSESOME
)TSREALLYSTILLA$OGOBJECT BUTIFYOUWANTTOCALL OFTHEMETHODSTOCODEOUTSIDETHECLASS4OEXPOSEA
And what’s so wrong with
staying an Object? OK, I can’t
$OG SPECIlCMETHODS YOUNEEDAREFERENCEDECLARED METHODMEANSYOUMAKEAMETHODACCESSIBLE USUALLYBY
fetch, sure, but I can give you
ASTYPE$OG)FYOURESURE
THEOBJECTISREALLYA MARKINGITPUBLIC
a real nice hashcode.
$OG YOUCANMAKEANEW$OGREFERENCETOITBY
COPYINGTHE/BJECTREFERENCE ANDFORCINGTHAT )MAGINETHISSCENARIOYOUREWRITINGCODEFORASMALL
COPYTOGOINTOA$OGREFERENCEVARIABLE USINGA BUSINESSACCOUNTINGPROGRAM!CUSTOMAPPLICATION
CAST$OG 9OUCANUSETHENEW$OGREFERENCETO FORh3IMONS3URF3HOPv4HEGOODRE
Account
CALL$OGMETHODS USERTHATYOUARE YOUFOUNDAN!CCOUNT
CLASSTHATAPPEARSTOMEETYOURNEEDS debit(double amt)
Object o = al.get(index);
PERFECTLY ACCORDINGTOITSDOCUMENTATION
ct back to ANYWAY%ACHACCOUNTINSTANCEREPRESENTS credit(double amt)
Dog d = (Dog) o;
ANINDIVIDUALCUSTOMERSACCOUNTWITHTHE
cast the Obknjeow is there.
d.roam(); aD og we double getBalance()
STORE3OTHEREYOUAREMINDINGYOUROWN
BUSINESSINVOKINGTHECREDIT ANDDEBIT
METHODSONANACCOUNTOBJECTWHENYOUREALIZEYOU
NEEDTOGETABALANCEONANACCOUNT.OPROBLEMˆ
THERESAGET"ALANCE METHODTHATSHOULDDONICELY
o %XCEPTWHENYOUINVOKETHEGET"ALANCE METHOD
D og t
objec THEWHOLETHINGBLOWSUPATRUNTIME&ORGETTHE
Object
DOCUMENTATION THECLASSDOESNOTHAVETHATMETHOD
9IKES
Cast the so-called ‘Object’ (but
we know he’s actually a Dog) to d "UTTHATWONTHAPPENTOYOU BECAUSEEVERYTIMEYOU
type Dog, so that you can treat USETHEDOTOPERATORONAREFERENCEADO3TUFF THE
Dog COMPILERLOOKSATTHEREFERENCETYPETHETYPE@AWAS
him like the Dog he really is.

)FYOURENOTSUREITSA$OG YOUCANUSETHE DECLAREDTOBE ANDCHECKSTHATCLASSTOGUARANTEETHE
instanceofOPERATORTOCHECK"ECAUSEIF CLASSHASTHEMETHOD ANDTHATTHEMETHODDOESINDEED
YOUREWRONGWHENYOUDOTHECAST YOULLGETA TAKETHEARGUMENTYOUREPASSINGANDRETURNTHEKINDOF
#LASS#AST%XCEPTIONATRUNTIMEANDCOMETOA VALUEYOUREEXPECTINGTOGETBACK
GRINDINGHALT *USTREMEMBERTHATTHECOMPILERCHECKSTHECLASSOFTHE
if (o instanceof Dog) { REFERENCEVARIABLE NOTTHECLASSOFTHEACTUALOBJECTATTHE
Dog d = (Dog) o; OTHERENDOFTHEREFERENCE
}

216 chapter 8 you are here4 217


modifying a class tree interfaces and polymorphism

Let’s explore some design options


What if you need to change for reusing some of our existing
the contract? classes in a PetShop program.
/NTHENEXTFEWPAGES WEREGOINGTOWALKTHROUGH
/+ PRETENDYOUREA$OG9OUR$OGCLASS
SOMEPOSSIBILITIES7ERENOTYETWORRIEDABOUT
ISNTTHEONLYCONTRACTTHATDElNESWHOYOU
WHETHER*AVACANACTUALLYDOWHATWECOMEUPWITH
ARE2EMEMBER YOUINHERITACCESSIBLEWHICH
7ELLCROSSTHATBRIDGEONCEWEHAVEAGOODIDEAOF
USUALLYMEANSPUBLIC METHODSFROMALLOF
SOMEOFTHETRADEOFFS
YOURSUPERCLASSES
4RUE YOUR$OGCLASSDElNESACONTRACT
"UTNOTALLOFYOURCONTRACT YiX`e
%VERYTHINGINCLASS#ANINEISPARTOFYOUR gfn\i
CONTRACT 1 Option one
%VERYTHINGINCLASS!NIMALISPARTOFYOUR We take the easy path, and put pet
CONTRACT Think about what YOU would do if YOU were methods in class Animal. t
%VERYTHINGINCLASS/BJECTISPARTOFYOUR the Dog class programmer and needed to the pe ere
Pros: put all d code up h
CONTRACT modify the Dog so that it could do Pet things,
All the Animals will instantly inherit metho heritance.
!CCORDINGTOTHE)3 !TEST YOUAREEACHOF too. We know that simply adding new Pet be- the pet behaviors. We won’t have to for in
THOSETHINGSˆ#ANINE !NIMAL AND/BJECT haviors (methods) to the Dog class will work, touch the existing Animal subclasses
and won’t break anyone else’s code. at all, and any Animal subclasses Animal
"UTWHATIFTHEPERSONWHODESIGNEDYOUR created in the future will also get to
CLASSHADINMINDTHE!NIMALSIMULATION But... this is a PetShop program. It has more take advantage of inheriting those
PROGRAM ANDNOWHEWANTSTOUSEYOUCLASS methods. That way, class Animal can
than just Dogs! And what if someone wants
$OG FORA3CIENCE&AIR4UTORIALON!NIMAL be used as the polymorphic type in
OBJECTS to use your Dog class for a program that has any program that wants to treat the
wild Dogs? What do you think your options Animals as pets Canine
4HATS/+ YOUREPROBABLYREUSABLEFORTHAT
might be, and without worrying about how Hippo
"UTWHATIFLATERHEWANTSTOUSEYOUFORA Cons:
Java handles things, just try to imagine how
0ET3HOPPROGRAM9OUDONTHAVEANY0ET So... when was the last time you
you’d like to solve the problem of modifying saw a Hippo at a pet shop? Lion? Feline
BEHAVIORS!0ETNEEDSMETHODSLIKEBE&RIENDLY
some of your Animal classes to include Pet Wolf? Could be dangerous to give
ANDPLAY 
behaviors. non-pets pet methods. Dog
/+ NOWPRETENDYOURETHE$OGCLASS
PROGRAMMER.OPROBLEM RIGHT*USTADD Stop right now and think about it, Also, we almost certainly WILL
SOMEMOREMETHODSTOTHE$OGCLASS9OU before you look at the next page where we have to touch the pet classes
Cat
WONTBEBREAKINGANYONEELSESCODEBY like Dog and Cat, because (in Wolf
begin to reveal everything. our house, anyway) Dogs
ADDINGMETHODS SINCEYOUARENTTOUCHING
THEEXISTINGMETHODSTHATSOMEONEELSESCODE and Cats tend to imple- Lion
(thus rendering the whole exercise completely useless, robbing
ment pet behaviors Tiger
MIGHTBECALLINGON$OGOBJECTS you of your One Big Chance to burn some brain calories) VERY differently.
#ANYOUSEEANYDRAWBACKSTOTHATAPPROACH
ADDING0ETMETHODSTOTHE$OGCLASS 

218 chapter 8 you are here4 219


modifying existing classes interfaces and polymorphism

3 Option three
Put the pet methods ONLY in the
classes where they belong.
2 Option t wo
We start with Option One, putting the pet methods Pros:
in class Animal, but we make the methods abstract, No more worries about Hippos greeting you at the
forcing the Animal subclasses to override them. door or licking your face. The methods are where
they belong, and ONLY where they belong. Dogs can
implement the methods and Cats can implement the LY in the
Pros: methods ON ,
methods, but nobody else has to know about them.
That would give us all the benefits of Option One, but with- ds Put the peastses that can be pets
out the drawback of having non-pet Animals running around metho Animal clof in Animal.
with pet methods (like beFriendly()). All Animal classes a ll t he petwith no all
Cons: instead
put ere, but ns. Make
would have the method (because it’s in class Animal), but up h mentatio abstract. Two Big Problems with this approach. First off, you’d
because it’s abstract the non-pet Animal classes won’t imple methods have to agree to a protocol, and all programmers of
inherit any functionality. All classes MUST override the pet pet Animal classes now and in the future would have
methods, but they can make the methods “do-nothings”. to KNOW about the protocol. By protocol, we mean Animal
the exact methods that we’ve decided all pets should
Animal have. The pet contract without anything to back it up.
Cons: But what if one of the programmers gets it just a tiny
Because the pet methods in the Animal class are all bit wrong? Like, a method takes a String when it was
abstract, the concrete Animal subclasses are forced to supposed to take an int? Or they named it doFriendly()
implement all of them. (Remember, all abstract methods instead of beFriendly()? Since it isn’t in a contract, Canine
MUST be implemented by the first concrete subclass the compiler has no way to check you to see if you’ve
Hippo
down the inheritance tree.) What a waste of time! Canine implemented the methods correctly. Someone
You have to sit there and type in each and every could easily come along to use the pet Animal
Hippo
pet method into each and every concrete non- classes and find that not all of them work Feline
pet class, and all future subclasses as well. quite right.
And while this does solve the problem of Feline Dog
non-pets actually DOING pet things And second, you don’t get to use
(as they would if they inherited pet Dog polymorphism for the pet methods.
functionality from class Animal), the Every class that needs to use
contract is bad. Every non-pet pet behaviors would have to Cat
Wolf
class would be announcing to the know about each and every
world that it, too, has those Cat class! In other words,
Wolf Lion
pet methods, even though you can’t use Animal
the methods wouldn’t Tiger
as the polymorphic
actually DO anything Lion
type now, because the
when called. Tiger
compiler won’t let you call
a Pet method on an Animal
This approach doesn’t reference (even if it’s really a
look good at all. It just Ask me to be friendly.
Dog object) because class Animal
seems wrong to stuff No, seriously... ask me.
doesn’t have the method.
everything into class Animal I have the method.
that more than one Animal type
might need, UNLESS it applies to
ALL Animal subclasses.

220 chapter 8 you are here4 221


multiple inheritance? interfaces and polymorphism

So what we REALLY need is: There’s just one problem with the “two superclasses” approach...
Æ A way to have pet behavior in just the pet classes
Æ A way to guarantee that all pet classes have all of the same It’s called “multiple inheritance”
methods defined (same name, same arguments, same return and it can be a Really Bad Thing.
types, no missing methods, etc.), without having to cross your
fingers and hope all the programmers get it right. That is, if it were possible to do in Java.
Æ A way to take advantage of polymorphism so that all pets can have But it isn’t, because multiple inheritance has a problem
their pet methods called, without having to use arguments, return known as The Deadly Diamond of Death.
types, and arrays for each and every pet class.

Deadly Diamond of Death


It looks like we need TWO
DigitalRecorder
superclasses at the top ner both int i
B ur ne r an d DVDBurorder,
ec
CD m DigitalR burn()
tract inherit fro erride the burn()
h ov
k e a n ew abs et, and
P
and bot oth inherit the “i”
We ma lass called t methods. method. B riable. ce
superc all the pe instance va CDBurner DVDBurner
“i” instanDBurner
give it Pet Animal hat the
Imagine tis used by both Cifferent
burn() burn()
variable Burner, with d ComboDrive
and DVDhat happens if of “i”?
values. W use both values
Canine
needs to
Hippo ComboDrive
Problem wit
Feline
Which burn()h multiple inheritance.
call burn() on method runs when you
Dog
the ComboD
rive?
Dog e
Cat Lion Wolf Pet anxtends both !LANGUAGETHATALLOWSTHE$EADLY$IAMONDOF$EATHCANLEADTO
SOMEUGLYCOMPLEXITIES BECAUSEYOUHAVETOHAVESPECIALRULESTO
d Anim
al
DEALWITHTHEPOTENTIALAMBIGUITIES!NDEXTRARULESMEANSEXTRA
nds Tiger WORKFORYOUBOTHINLEARNINGTHOSERULESANDWATCHINGOUTFOR
Cat now extenimal
THOSEhSPECIALCASESv*AVAISSUPPOSEDTOBESIMPLE WITHCONSISTENT
from both A it gets RULESTHATDONTBLOWUPUNDERSOMESCENARIOS3O*AVAUNLIKE
AND Pet, so of both. # PROTECTSYOUFROMHAVINGTOTHINKABOUTTHE$EADLY$IA
the methods The non-pet Animals MONDOF$EATH"UTTHATBRINGSUSBACKTOTHEORIGINALPROBLEM
don’t have any inherited (OWDOWEHANDLETHE!NIMAL0ETTHING
Pet stuff.

222 chapter 8 you are here4 223


interfaces interfaces and polymorphism

Interface to the rescue! Making and Implementing interface me


*AVAGIVESYOUASOLUTION!NINTERFACE.OTA'5)INTERFACE NOTTHEGENERIC the Pet interface abstract, so thods are implicitly public an
USEOFTHEWORDINTERFACEASIN h4HATSTHEPUBLICINTERFACEFORTHE"UTTON is optional (intyfapinctg in ‘public’ and ‘abstractd ’
CLASS!0) vBUTTHE*AVAKEYWORDinterface style’ to type e , it’s not considered ‘good
words in, but we
d just to reinforth did here
!*AVAINTERFACESOLVESYOURMULTIPLEINHERITANCEPROBLEMBYGIVINGYOU rface’ instea been slaves to faceshiit, and because we’ve never
MUCHOFTHEPOLYMORPHICBENElTSOFMULTIPLEINHERITANCEWITHOUTTHEPAIN
You say ‘inhetere
’ on...)
of ‘class
ANDSUFFERINGFROMTHE$EADLY$IAMONDOF$EATH$$$ 
4HEWAYINWHICHINTERFACESSIDE STEPTHE$$$ISSURPRISINGLYSIMPLEMAKE
methods are
public interface Pet { All interface they MUST end in
ALLTHEMETHODSABSTRACT4HATWAY THESUBCLASSMUSTIMPLEMENTTHEMETHODS abstract, so emember, they have
REMEMBER ABSTRACTMETHODSMUSTBEIMPLEMENTEDBYTHElRSTCONCRETE public abstract void beFriendly(); semicolons. R
SUBCLASS SOATRUNTIMETHE*6-ISNTCONFUSEDABOUTWHICHOFTHETWO
INHERITEDVERSIONSITSSUPPOSEDTOCALL public abstract void play(); no body!
}
Pet A Java interface is like a s’
100% pure abstract class.
nimal You say ‘implethmee nt me
Dog IS-AISA-A Pet followed by facena.
and Dog public class Dog extends Canine implements Pet { of th
e inter
abstract void beFriendly(); e are
in an interfac
abstract void play(); All methods any class that IS-A public void beFriendly() {...}
You SAID
public void play() {..}
abstract, so implement (i.e. override)
implement you are a Pet, so yo M
Pet MUST of Pet. UST
the methods contract. Nthote Pet methods. It’su yo
instead of se ice the curly braces ur
micolons.
public void roam() {...}

public void eat() {...} These are just norma


l
overriding meth ods.
To DEFINE an interface: }
public interface Pet {...}
there are no
Dumb Questions
TYPES YOUCANPASSANYTHINGTHAT TOEXTEND9OUCOULDJUSTGIVETHEM
Use the ke
instead of yword “interface” Q: 7AITAMINUTE INTERFACESDONT IMPLEMENTSTHATINTERFACE!NDTHINK THEINTERFACEANDSAY h(ERE )DONT
“class” REALLYGIVEYOUMULTIPLEINHERITANCE ABOUTITˆWITHANINTERFACE ACLASS CAREWHATKINDOFCLASSINHERITANCE
BECAUSEYOUCANTPUTANY DOESNTHAVETOCOMEFROMJUSTONE STRUCTUREYOUCOMEFROM JUST
IMPLEMENTATIONCODEINTHEM)FALL INHERITANCETREE!CLASSCANEXTEND IMPLEMENTTHISINTERFACEANDYOULLBE
To IMPLEMENT an interface: THEMETHODSAREABSTRACT WHATDOES ONECLASS ANDIMPLEMENTANINTERFACE GOODTOGOv
ANINTERFACEREALLYBUYYOU "UTANOTHERCLASSMIGHTIMPLEMENT 4HEFACTTHATYOUCANTPUTIN
public class Dog extends Canine implements Pet {...} THESAMEINTERFACE YETCOMEFROMA IMPLEMENTATIONCODETURNSOUTNOTTO
COMPLETELYDIFFERENTINHERITANCETREE BEAPROBLEMFORMOSTGOODDESIGNS
followed A: 0OLYMORPHISM POLYMORPHISM 3OYOUGETTOTREATANOBJECTBYTHE BECAUSEMOSTINTERFACEMETHODS
d “implements” POLYMORPHISM)NTERFACESARETHE ROLEITPLAYS RATHERTHANBYTHECLASS WOULDNTMAKESENSEIFIMPLEMENTED
ULTIMATEINFLEXIBILITY BECAUSEIFYOU TYPEFROMWHICHITWASINSTANTIATED
Use the keywor e name. Note that
INAGENERICWAY)NOTHERWORDS MOST
by the interfac ent an interface you USEINTERFACESINSTEADOFCONCRETE )NFACT IFYOUWROTEYOURCODETOUSE INTERFACEMETHODSWOULDNEEDTO
when you implem nd a class SUBCLASSESOREVENABSTRACTSUPERCLASS INTERFACES YOUWOULDNTEVENHAVETO BEOVERRIDDENEVENIFTHEMETHODS
still get to exte TYPES ASARGUMENTSANDRETURN GIVEANYONEASUPERCLASSTHATTHEYHAD WERENTFORCEDTOBEABSTRACT

224 chapter 8 you are here4 225


interface polymorphism interfaces and polymorphism

Classes from different inheritance trees


can implement the same interface.
Robot

Pet Animal
tick
Make it S
BLUE
Agent IOLETSARE TTWO
RERED V IM PLEMEN
RoboDog 2OSESA E B U T
Canine
ONLYON
%X TEND
VALUES
NFAMILY AVE
Class RoboDo Hippo IGHSINO SCANH
esn’t *AVAWE  ! AVACLAS ENT
come from thge do ARE N TS / NLY * ANDTHATPAR
imal LASS IMPLE
inheritance treeAn
, 3INGLE0 ARENTSUPERC
E P RE  " U T YOUCAN ACES
Feline TERF
ONLYON ESWHOYOUA
FIN HOSEIN
S ANDT
gets to be a Pet!but it still
CLASSDE IPLEINTERFACE
T M U LT LA Y
Dog ME N CAN P
OLESYOU
DEFINER

Cat Lion Wolf


How do you know whether to make a
class, a subclass, an abstract class, or
an interface?
Tiger

Make a class that doesn’t extend anything


 (other than Object) when your new class doesn’t
pass the IS-A test for any other type.

7HENYOUUSEACLASSASAPOLYMORPHICTYPELIKEAN THEIRMETHODSINASEPARATETHREADOFEXECUTION Make a subclass (in other words, extend a class)


ARRAYOFTYPE!NIMALORAMETHODTHATTAKESA#ANINE )MPLEMENT2UNNABLE9OUGETTHEIDEA9OULL
 only when you need to make a more specific
version of a class and need to override or add
ARGUMENT THEOBJECTSYOUCANSTICKINTHATTYPE LEARNMOREABOUT3ERIALIZABLEAND2UNNABLEINLATER
new behaviors.
MUSTBEFROMTHESAMEINHERITANCETREE"UTNOTJUST CHAPTERS BUTFORNOW REMEMBERTHATCLASSESFROM
ANYWHEREINTHEINHERITANCETREETHEOBJECTSMUSTBE ANYPLACEINTHEINHERITANCETREEMIGHTNEEDTO Use an abstract class when you want to define
FROMACLASSTHATISASUBCLASSOFTHEPOLYMORPHICTYPE IMPLEMENTTHOSEINTERFACES.EARLYANYCLASSMIGHT  a template for a group of subclasses, and you
!NARGUMENTOFTYPE#ANINECANACCEPTA7OLFANDA WANTTOBESAVEABLEORRUNNABLE have at least some implementation code that all
$OG BUTNOTA#ATORA(IPPO subclasses could use. Make the class abstract
Better still, a class can implement when you want to guarantee that nobody can
"UTWHENYOUUSEANINTERFACEASAPOLYMORPHIC multiple interfaces! make objects of that type.
TYPELIKEANARRAYOF0ETS THEOBJECTSCANBE
FROMANYWHEREINTHEINHERITANCETREE4HEONLY !$OGOBJECT)3 !#ANINE AND)3 !!NIMAL AND Use an interface when you want to define a role
REQUIREMENTISTHATTHEOBJECTSAREFROMACLASSTHAT )3 !/BJECT ALLTHROUGHINHERITANCE"UTA$OG)3 !  that other classes can play, regardless of where
IMPLEMENTSTHEINTERFACE!LLOWINGCLASSESINDIFFERENT 0ETTHROUGHINTERFACEIMPLEMENTATION ANDTHE$OG those classes are in the inheritance tree.
INHERITANCETREESTOIMPLEMENTACOMMONINTERFACE MIGHTIMPLEMENTOTHERINTERFACESASWELL9OUCOULD
ISCRUCIALINTHE*AVA!0)$OYOUWANTANOBJECT SAY
TOBEABLETOSAVEITSSTATETOAlLE)MPLEMENTTHE public class Dog extends Animal implements
3ERIALIZABLEINTERFACE$OYOUNEEDOBJECTSTORUN Pet, Saveable, Paintable { ... }

226 chapter 8 you are here4 227


using super interfaces and polymorphism

Invoking the superclass the BULLET POINTS


version of Q: 4HERESSTILLSOMETHING
version of a method superclass oes important stuff STRANGEHEREYOUNEVER
d
method lasses could use When you don’t want a class to be instantiated (in other words, you don’t EXPLAINEDHOWITISTHAT
Q: 7HATIFYOUMAKEACONCRETESUBCLASS abstract class Report { that subc  want anyone to make a new object of that class type) mark the class with the !RRAY,IST$OGGIVESBACK$OG
ANDYOUNEEDTOOVERRIDEAMETHOD BUTYOU void runReport() { abstract keyword. REFERENCESTHATDONTNEEDTOBE
// set-up report CAST YETTHE!RRAY,ISTCLASSUSES
WANTTHEBEHAVIORINTHESUPERCLASSVERSIONOF
} An abstract class can have both abstract and non-abstract methods. /BJECTINITSMETHODS NOT$OG
THEMETHOD)NOTHERWORDS WHATIFYOUDONT void printReport() {

If a class has even one abstract method, the class must be marked abstract. OR$OT#OMORANYTHINGELSE 
NEEDTOREPLACETHEMETHODWITHANOVERRIDE // generic printing  7HATSTHESPECIALTRICKGOINGON
BUTYOUJUSTWANTTOADDTOITWITHSOME } An abstract method has no body, and the declaration ends with a semicolon (no WHENYOUSAY!RRAY,IST$OG
ADDITIONALSPECIlCCODE }  curly braces).
class BuzzwordsReport extends Report { All abstract methods must be implemented in the first concrete subclass in the
 A: 9OURERIGHTFORCALLINGITA
A: !HHHTHINKABOUTTHEMEANINGOFTHE inheritance tree. SPECIALTRICK)NFACTITISASPECIAL
WORD@EXTENDS/NEAREAOFGOOD//DESIGNLOOKS void runReport() { ss version,
Every class in Java is either a direct or indirect subclass of class Object (java.lang. TRICKTHAT!RRAY,IST$OGGIVES
ATHOWTODESIGNCONCRETECODETHATSMEANTTO super.runReport(); call supercelaback and
m
BEOVERRIDDEN)NOTHERWORDS YOUWRITEMETHOD buzzwordCompliance(); th en co  Object).
BACK$OGSWITHOUTYOUHAVING
lass- TODOANYCAST SINCEITLOOKSLIKE
CODEIN SAY ANABSTRACTCLASS THATDOESWORK printReport(); do some subc f Methods can be declared with Object arguments and/or return types. !RRAY,ISTMETHODSDONTKNOW
THATSGENERICENOUGHTOSUPPORTTYPICALCONCRETE specific stuf  ANYTHINGABOUT$OGS ORANYTYPE
IMPLEMENTATIONS"UT THECONCRETECODEISNT } You can call methods on an object only if the methods are in the class (or interface) BESIDES/BJECT
ENOUGHTOHANDLEALLOFTHESUBCLASS SPECIFIC void buzzwordCompliance() {...}  used as the reference variable type, regardless of the actual object type. So, a
WORK3OTHESUBCLASSOVERRIDESTHEMETHOD } 4HESHORTANSWERISTHATTHE
reference variable of type Object can be used only to call methods defined in class COMPILERPUTSINTHECASTFORYOU
ANDEXTENDSITBYADDINGTHERESTOFTHECODE
4HEKEYWORDSUPERLETSYOUINVOKEASUPERCLASS Object, regardless of the type of the object to which the reference refers. 7HENYOUSAY!RRAY,IST$OG
VERSIONOFANOVERRIDDENMETHOD FROMWITHINTHE A reference variable of type Object can’t be assigned to any other reference type THEREISNOSPECIALCLASSTHATHAS
SUBCLASS  METHODSTOTAKEANDRETURN$OG
without a cast. A cast can be used to assign a reference variable of one type to a
OBJECTS BUTINSTEADTHE$OG
If method code inside a reference variable of a subtype, but at runtime the cast will fail if the object on the ISASIGNALTOTHECOMPILERTHAT
BuzzwordReport subclass says: rrides heap is NOT of a type compatible with the cast. YOUWANTTHECOMPILERTOLET
sub c lass m ethod (osiveon)
Example: Dog d = (Dog) x.getObject(aDog); YOUPUT/.,9$OGOBJECTSIN
super.runReport(); class ver ANDTOSTOPYOUIFYOUTRYTOADD
the super All objects come out of an ArrayList<Object> as type Object (meaning, they can be
the runReport() method inside  ANYOTHERTYPETOTHELIST!ND
runReport() referenced only by an Object reference variable, unless you use a cast). SINCETHECOMPILERSTOPSYOU
the superclass Report will run buzzwordCompliance() FROMADDINGANYTHINGBUT$OGS
superclass methods en Multiple inheritance is not allowed in Java, because of the problems associated with
(including the overridd  TOTHE!RRAY,IST THECOMPILER
runReport() the “Deadly Diamond of Death”. That means you can extend only one class (i.e. you
ALSOKNOWSTHATITSSAFETOCAST
printReport() runReport() can have only one immediate superclass). ANYTHINGTHATCOMESOUTOFTHAT
Report An interface is like a 100% pure abstract class. It defines only abstract methods. !RRAY,ISTDOA$OGREFERENCE)N
 OTHERWORDS USING!RRAY,IST$OG
super.runReport(); Create an interface using the interface keyword instead of the word class. SAVESYOUFROMHAVINGTOCAST
BuzzwordReport 
A reference to the subclass object THE$OGYOUGETBACK"UTITS
Implement an interface using the keyword implements MUCHMOREIMPORTANTTHANTHAT
(BuzzwordReport) will always call  Example: Dog implements Pet BECAUSEREMEMBER ACASTCAN
the subclass version of an overridden Your class can implement multiple interfaces. FAILATRUNTIME ANDWOULDNTYOU
method. That’s polymorphism. The super keyword is really a reference  RATHERHAVEYOURERRORSHAPPEN
to the superclass portion of an object. A class that implements an interface must implement all the methods of the ATCOMPILETIMERATHERTHAN SAY
But the subclass code can call  interface, since all interface methods are implicitly public and abstract. WHENYOURCUSTOMERISUSINGITFOR
super.runReport() to invoke the When subclass code uses super, as in SOMETHINGCRITICAL
superclass version. super.runReport(), the superclass version of To invoke the superclass version of a method from a subclass that’s overridden the
 "UTTHERESALOTMORETOTHISSTORY
the method will run. method, use the super keyword. Example: super.runReport(); ANDWELLGETINTOALLTHEDETAILSIN
THE#OLLECTIONSCHAPTER

228 chapter 8 you are here4 229


exercise: What’s the Picture? interfaces and polymorphism

(ERESYOURCHANCETODEMONSTRATEYOURARTISTICABILITIES/NTHELEFTYOULL /NTHELEFTYOULLlNDSETSOFCLASSDIAGRAMS9OURJOBISTOTURN
1dQ^OU_Q 1dQ^OU_Q
lNDSETSOFCLASSANDINTERFACEDECLARATIONS9OURJOBISTODRAWTHEASSOCIATED THESEINTOVALID*AVADECLARATIONS7EDIDNUMBERFORYOU
CLASSDIAGRAMSONTHERIGHT7EDIDTHElRSTONEFORYOU5SEADASHEDLINEFOR ANDITWASATOUGHONE 
hIMPLEMENTSvANDASOLIDLINEFORhEXTENDSv
What’s the Declaration ?
Given: What’s the Picture ? Given:
(interface) Click 1) public class Click { }
1) Foo 1
1) public interface Foo { } public class Clack extends Click { }
public class Bar implements Foo { } Top
2
2)
2) Clack
2) public interface Vinn { }
public abstract class Vout implements Vinn { } Bar

Tip
3)

3) public abstract class Muffie implements Whuffie { } Fee


public class Fluffie extends Muffie { } 3) 3
public interface Whuffie { } 4)
Foo
4
Fi

4) public class Zoop { } 4)


public class Boop extends Zoop { }
Bar 5)
public class Goop extends Boop { }

Zeta
5
5) public class Gamma extends Delta implements Epsilon { }
Baz
public interface Epsilon { }
5) Beta
public interface Beta { }
Alpha KEY
public class Alpha extends Gamma implements Beta { }
EXTENDS
public class Delta { }
IMPLEMENTS
Clack CLASS
Delta
Clack INTERFACE

Clack ABSTRACTCLASS

230 chapter 8 you are here4 231


puzzle: Pool Puzzle interfaces and polymorphism

9OURJOBISTOTAKECODESNIPPETSFROMTHEPOOLAND
Pool PLACETHEMINTOTHEBLANKLINESINTHECODEANDOUT
%XERCISE3OLUTIONS
PUT9OUMAYUSETHESAMESNIPPETMORETHANONCE
Puzzle ANDYOUWONTNEEDTOUSEALLTHESNIPPETS9OUR
GOALISTOMAKEASETOFCLASSESTHATWILLCOMPILE
ANDRUNANDPRODUCETHEOUTPUTLISTED
What’s the Picture ?

(interface)
____________ Nose {
2) Vinn
public ___________ ________ extends Clowns { (interface)
________________________
3) Whuffie

} public static void main(String [] args) {


____________________________ Vout What’s the Declaration ?
abstract class Picasso implements ______{ Muffie
i[0] = new __________
_________________________
i[1] = new __________ 2) public abstract class Top { }
return 7;
} i[2] = new __________ public class Tip extends Top { }
} for(int x = 0; x < 3; x++) { 4) Zoop Fluffie

System.out.println(__________________ 3) public abstract class Fee { }


class _________ ________ __________ { } + “ “ + _______.getClass( ) ); public abstract class Fi extends Fee { }
} Boop
class _________ ________ __________ { } public interface Foo { }
___________________________ } /UTPUT File Edit Window Help BeAfraid
4)
return 5; %java ______________
public class Bar implements Foo { }
} 5 class Acts Goop public class Baz extends Bar { }
} 7 class Clowns
________Of76
.OTE%ACHSNIPPET 5) public interface Zeta { }
FROMTHEPOOLCANBE 5) (interface) public class Alpha implements Zeta { }
Delta Epsilon
USEDMORETHANONCE
CLASS public interface Beta { }
!CTS  EXTENDS I
.OSE  INTERFACE I (interface)
public class Delta extends Alpha implements Beta { }
/F  IMPLEMENTS IX Gamma Beta
#LOWNS  I;X= CLASS
0ICASSO  CLASS
CLASS !CTS
PUBLICINTI-ETHOD  PUBLICCLASS .OSE
/F;=INEW.OSE;= PUBLICINTI-ETHOD[] /F
/F;=I PUBLICINTI-ETHOD [ II-ETHODX #LOWNS Alpha
.OSE;=INEW.OSE  PUBLICINTI-ETHOD [] IX I-ETHOD;= 0ICASSO
.OSE;=INEW.OSE;= I;X=I-ETHOD
I;X=I-ETHOD;=

232 chapter 8 you are here4 233


puzzle solution

interface Nose { public class Of76 extends Clowns {


public int iMethod( ) ; public static void main(String [] args) {
} Nose [ ] i = new Nose [3] ;
abstract class Picasso implements Nose { i[0] = new Acts( ) ;
public int iMethod( ) { i[1] = new Clowns( ) ;
return 7;
i[2] = new Of76( ) ;
}
for(int x = 0; x < 3; x++) {
}
class Clowns extends Picasso { } System.out.println( i [x] . iMethod( )
+ “ “ + i [x].getClass( ) );
class Acts extends Picasso { }
public int iMethod( ) { }
return 5; }
}
}

/UTPUT File Edit Window Help KillTheMime

%java Of76
5 class Acts
7 class Clowns
7 class Of76

234 chapter 8

Potrebbero piacerti anche