Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
BSPVOE DEPENDS ON KNOWING *AVA
ix
,BUIZ4JFSSB#FSU#BUFT
Breaking the Surface Know Your Variables
Java takes you to new places. &ROM ITS HUMBLE RELEASE TO THE PUBLIC AS THE Variables come in two flavors: primitive and reference.
WIMPY VERSION *AVA SEDUCED PROGRAMMERS WITH ITS FRIENDLY SYNTAX OBJECT
ORIENTED 4HERES GOTTA BE MORE TO LIFE THAN INTEGERS 3TRINGS AND ARRAYS 7HAT IF YOU HAVE A 0ET/WNER
1 FEATURES MEMORY MANAGEMENT AND BEST OF ALLTHE PROMISE OF PORTABILITY 7ELL TAKE A QUICK
3 OBJECT WITH A $OG INSTANCE VARIABLE /R A #AR WITH AN %NGINE )N THIS CHAPTER WELL UNWRAP
DIP AND WRITE SOME CODE COMPILE IT AND RUN IT 7ERE TALKING SYNTAX LOOPS BRANCHING AND WHAT THE MYSTERIES OF *AVA TYPES AND LOOK AT WHAT YOU CAN DECLARE AS A VARIABLE WHAT YOU CAN PUT
MAKES *AVA SO COOL $IVE IN IN A VARIABLE AND WHAT YOU CAN DO WITH A VARIABLE !ND WELL FINALLY SEE WHAT LIFE IS TRULY LIKE
ON THE GARBAGE
COLLECTIBLE HEAP
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
x xi
Extra-Strength Methods Better Living in Objectville
Let’s put some muscle in our methods. 9OU DABBLED WITH VARIABLES Plan your programs with the future in mind. 7HAT IF YOU COULD WRITE
PLAYED WITH A FEW OBJECTS AND WROTE A LITTLE CODE "UT YOU NEED MORE TOOLS ,IKE CODE THAT SOMEONE ELSE COULD EXTEND EASILY 7HAT IF YOU COULD WRITE CODE THAT WAS FLEXIBLE
5 OPERATORS !ND LOOPS -IGHT BE USEFUL TO GENERATE RANDOM NUMBERS !ND TURN
7 FOR THOSE PESKY LAST
MINUTE SPEC CHANGES 7HEN YOU GET ON THE 0OLYMORPHISM 0LAN YOULL
A 3TRING INTO AN INT YEAH THAT WOULD BE COOL !ND WHY DONT WE LEARN IT ALL BY BUILDING LEARN THE STEPS TO BETTER CLASS DESIGN THE TRICKS TO POLYMORPHISM THE WAYS TO MAKE
SOMETHING REAL TO SEE WHAT ITS LIKE TO WRITE AND TEST A PROGRAM FROM SCRATCH -AYBE A FLEXIBLE CODE AND IF YOU ACT NOWA BONUS LESSON ON THE TIPS FOR EXPLOITING INHERITANCE
a build the GAME LIKE 3INK A $OT #OM SIMILAR TO "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 2OSES ARE RED
IS-A and HAS-A (bathtub girl) 177
#
VIOLETS ARE BL
3QUARE )3
! 3 UE
Coding the Simple Dot Com game 103 HAPE THE REV
'OCOM
$ 0ETSCOM ERSE ISNT TRUE
What do you inherit from your superclass? 180
2OSES ARE RED
Final code for Simple Dot Com 106 VIOLETS ARE DE
AR What does inheritance really buy you? 182
% "EER )3
! $RIN
K BUT NOT ALL
Generating random numbers with Math.random() 111 DRINKS ARE BE
ER Polymorphism (using a supertype reference to a subclass object) 183
& /+ YOUR TURN
-
Ready-bake code for getting user input from the command-line 112 WAY
NESS OF TH AKE ONE THAT SHOWS THE Rules for overriding (don’t touch those arguments and return types!) 190
' !SK-ECOM E ) ONE
Looping with for loops 114 BER IF 8 EX TEN 3
! RELATIONSHIP !ND R
DS 9 8 )3
! 9 EMEM
Method overloading (nothing more than method name re-use) 191
MUST MAKE SE
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. 4O EXPLOIT POLYMORPHISM WE NEED
Java ships with hundreds of pre-built classes. 9OU DONT HAVE TO INTERFACES 7E NEED TO GO BEYOND SIMPLE INHERITANCE TO FLEXIBILITY YOU CAN GET ONLY BY
REINVENT THE WHEEL IF YOU KNOW HOW TO FIND WHAT YOU NEED FROM THE *AVA LIBRARY COMMONLY DESIGNING AND CODING TO INTERFACES 7HATS AN INTERFACE ! ABSTRACT CLASS 7HATS AN
6 8 ABSTRACT CLASS ! CLASS THAT CANT BE INSTANTIATED 7HATS THAT GOOD FOR 2EAD THE CHAPTER
KNOWN AS THE *AVA !0) 9OUVE GOT BETTER THINGS TO DO )F YOURE GOING TO WRITE CODE YOU
MIGHT AS WELL WRITE ONLY THE PARTS THAT ARE CUSTOM FOR YOUR APPLICATION 4HE CORE *AVA LIBRARY
Some classes just should not be instantiated 200
IS A GIANT PILE OF CLASSES JUST WAITING FOR YOU TO USE LIKE BUILDING BLOCKS
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'OOD TO KNOW THERES AN !RRAY,IST IN ArrayList (taking advantage of the Java API) 132 d.bark(); Polymorphism in action 206
THE JAVAUTIL PACKAGE "UT BY MYSELF HOW Fixing the DotCom class code 138 Class Object (the ultimate superclass of everything) 208
WOULD ) HAVE l GURED THAT OUTv
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. 9OURE IN CHARGE 9OU DECIDE WHEN AND Stuff happens. 4HE FILE ISNT THERE 4HE SERVER IS DOWN .O MATTER HOW GOOD A
HOW TO CONSTRUCT THEM 9OU DECIDE WHEN TO ABANDON THEM 4HE 'ARBAGE #OLLECTOR GC PROGRAMMER YOU ARE YOU CANT CONTROL EVERYTHING 7HEN YOU WRITE A RISKY METHOD YOU NEED
9 RECLAIMS THE MEMORY 7ELL LOOK AT HOW OBJECTS ARE CREATED WHERE THEY LIVE AND HOW TO
11 CODE TO HANDLE THE BAD THINGS THAT MIGHT HAPPEN "UT HOW DO YOU KNOW WHEN A METHOD IS
KEEP OR ABANDON THEM EFFICIENTLY 4HAT MEANS WELL TALK ABOUT THE HEAP THE STACK SCOPE RISKY 7HERE DO YOU PUT THE CODE TO HANDLE THE EXCEPTIONAL SITUATION )N THIS CHAPTER WERE
CONSTRUCTORS SUPER CONSTRUCTORS NULL REFERENCES AND GC ELIGIBILITY GOING TO BUILD A -)$) -USIC 0LAYER THAT USES THE RISKY *AVA3OUND !0) SO WE BETTER FIND OUT
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
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. 5NLESS YOU ACTUALLY CARE WHERE EVERYTHING GOES 3WING CODE LOOKS Connect with the outside world. )TS EASY !LL THE LOW
LEVEL NETWORKING
EASY BUT THEN COMPILE IT RUN IT LOOK AT IT AND THINK hHEY THATS NOT SUPPOSED TO GO THEREv DETAILS ARE TAKEN CARE OF BY CLASSES IN THE JAVANET LIBRARY /NE OF *AVAS BEST FEATURES IS
4HE THING THAT MAKES IT EASY TO CODE IS THE THING THAT MAKES IT HARD TO CONTROLTHE ,AYOUT
13 15 THAT SENDING AND RECEIVING DATA OVER A NETWORK IS REALLY JUST )/ WITH A SLIGHTLY DIFFERENT
-ANAGER "UT WITH A LITTLE WORK YOU CAN GET LAYOUT MANAGERS TO SUBMIT TO YOUR WILL )N CONNECTION STREAM AT THE END OF THE CHAIN )N THIS CHAPTER WELL MAKE CLIENT SOCKETS 7ELL
THIS CHAPTER WELL WORK ON OUR 3WING AND LEARN MORE ABOUT WIDGETS MAKE SERVER SOCKETS 7ELL MAKE CLIENTS AND SERVERS "EFORE THE CHAPTERS DONE YOULL HAVE A
FULLY
FUNCTIONAL MULTITHREADED CHAT CLIENT $ID WE JUST SAY MULTITHREADED
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. /BJECTS HAVE STATE AND BEHAVIOR The runnable-running loop 496
"EHAVIOR LIVES IN THE CLASS BUT STATE LIVES WITHIN EACH INDIVIDUAL OBJECT )F YOUR PROGRAM Thread scheduler (it’s his decision, not yours) 497
Putting a thread to sleep 501
14 NEEDS TO SAVE STATE YOU CAN DO IT THE HARD WAY INTERROGATING EACH OBJECT PAINSTAKINGLY
WRITING THE VALUE OF EACH INSTANCE VARIABLE /R YOU CAN DO IT THE EASY // WAYYOU SIMPLY Making and starting two threads 503
FREEZE
DRY THE OBJECT SERIALIZE IT AND RECONSTITUTE DESERIALIZE IT TO GET IT BACK 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. 9OU HAVE ALL THE TOOLS FOR COLLECTING AND MANIPULATING Being remote doesn’t have to be a bad thing. 3URE THINGS ARE EASIER
YOUR DATA WITHOUT HAVING TO WRITE YOUR OWN SORT ALGORITHMS 4HE *AVA #OLLECTIONS WHEN ALL THE PARTS OF YOUR APPLICATION ARE IN ONE PLACE IN ONE HEAP WITH ONE *6- TO RULE
16 &RAMEWORK HAS A DATA STRUCTURE THAT SHOULD WORK FOR VIRTUALLY ANYTHING YOULL EVER NEED
18 THEM ALL "UT THATS NOT ALWAYS POSSIBLE /R DESIRABLE 7HAT IF YOUR APPLICATION HANDLES
TO DO 7ANT TO KEEP A LIST THAT YOU CAN EASILY KEEP ADDING TO 7ANT TO FIND SOMETHING BY POWERFUL COMPUTATIONS 7HAT IF YOUR APP NEEDS DATA FROM A SECURE DATABASE )N THIS
NAME 7ANT TO CREATE A LIST THAT AUTOMATICALLY TAKES OUT ALL THE DUPLICATES 3ORT YOUR CO
CHAPTER WELL LEARN TO USE *AVAS AMAZINGLY SIMPLE 2EMOTE -ETHOD )NVOCATION 2-) 7ELL
WORKERS BY THE NUMBER OF TIMES THEYVE STABBED YOU IN THE BACK ALSO TAKE A QUICK PEEK AT 3ERVLETS %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. !LL THE CODE FOR THE FULL CLIENT
SERVER CHAT
BEAT BOX 9OUR CHANCE TO BE A ROCK STAR
Release Your Code
It’s time to let go. 9OU WROTE YOUR CODE 9OU TESTED YOUR CODE 9OU REFINED YOUR CODE
A
BeatBoxFinal (client code) 650
9OU TOLD EVERYONE YOU KNOW THAT IF YOU NEVER SAW A LINE OF CODE AGAIN THATD BE FINE "UT IN MusicServer (server code) 657
DANCE BEAT
17 THE END YOUVE CREATED A WORK OF ART 4HE THING ACTUALLY RUNS "UT NOW WHAT )N THESE FINAL
TWO CHAPTERS WELL EXPLORE HOW TO ORGANIZE PACKAGE AND DEPLOY YOUR *AVA CODE 7ELL LOOK !NDY GROOVE
REVISED
#HRIS GROOVE
BEAT
.IGEL DANCE
AT LOCAL SEMI
LOCAL AND REMOTE DEPLOYMENT OPTIONS INCLUDING EXECUTABLE JARS *AVA 7EB
3TART 2-) AND 3ERVLETS 2ELAX 3OME OF THE COOLEST THINGS IN *AVA ARE EASIER THAN YOU THINK
classes
Running an executable JAR 586 The Top Ten Things that didn’t make it into the book. 7E CANT SEND
MyApp.class
Put your classes in a package! 587 YOU OUT INTO THE WORLD JUST YET 7E HAVE A FEW MORE THINGS FOR YOU BUT THIS IS THE END OF THE
Packages must have a matching directory structure 589
B BOOK !ND THIS TIME WE REALLY MEAN IT
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
NCE UPON A TIME IN A SOFTWARE SHOP TWO
PROGRAMMERS WERE GIVEN THE SAME SPEC AND TOLD TO
A Trip to Objectville hBUILD ITv 4HE 2EALLY !NNOYING 0ROJECT -ANAGER
O FORCED THE TWO CODERS TO COMPETE
BY PROMISING THAT WHOEVER DELIVERS
lRST GETS ONE OF THOSE COOL !ERON©
CHAIRS ALL THE 3ILICON 6ALLEY GUYS HAVE
,ARRY THE PROCEDURAL PROGRAMMER AND
We’re going to "RAD THE // GUY BOTH KNEW THIS WOULD
Objectville! We’re BE A PIECE OF CAKE
leaving this dusty ol’
procedural town for good. ,ARRY SITTING IN HIS CUBE THOUGHT TO
I’ll send you a postcard. HIMSELF h7HAT ARE THE THINGS THIS PROGRAM
HAS TO DO 7HAT PROCEDURES DO WE NEEDv
!ND HE ANSWERED HIMSELF hROTATE AND
PLAY3OUNDv 3O OFF HE WENT TO BUILD THE
PROCEDURES !FTER ALL WHAT IS A PROGRAM IF NOT
A PILE OF PROCEDURES
"RAD MEANWHILE KICKED BACK AT THE CAFE
AND THOUGHT TO HIMSELF h7HAT ARE THE THINGS
IN THIS PROGRAM WHO ARE THE KEY PLAYERSv (E
lRST THOUGHT OF 4HE 3HAPES /F COURSE THERE
WERE OTHER OBJECTS HE THOUGHT OF LIKE THE 5SER THE 3OUND
AND THE #LICKING EVENT "UT HE ALREADY HAD A LIBRARY OF CODE
FOR THOSE PIECES SO HE FOCUSED ON BUILDING 3HAPES 2EAD
ON TO SEE HOW "RAD AND ,ARRY BUILT THEIR PROGRAMS AND the chair
FOR THE ANSWER TO YOUR BURNING QUESTION h3O WHO GOT THE
!ERONv
I was told there would be objects. )N CHAPTER WE PUT ALL OF OUR CODE IN THE
MAIN METHOD 4HATS NOT EXACTLY OBJECT
ORIENTED )N FACT THATS NOT OBJECT
ORIENTED AT ALL 7ELL In Larry’s cube At Brad’s laptop at the cafe
WE DID USE A FEW OBJECTS LIKE THE 3TRING ARRAYS FOR THE 0HRASE
/
-ATIC BUT WE DIDNT ACTUALLY !S HE HAD DONE A GAZILLION TIMES BEFORE ,ARRY "RAD WROTE A CLASS FOR EACH OF THE THREE SHAPES
DEVELOP ANY OF OUR OWN OBJECT TYPES 3O NOW WEVE GOT TO LEAVE THAT PROCEDURAL WORLD BEHIND SET ABOUT WRITING HIS )MPORTANT 0ROCEDURES
(E WROTE ROTATE AND PLAY3OUND IN NO TIME
GET THE HECK OUT OF MAIN AND START MAKING SOME OBJECTS OF OUR OWN 7ELL LOOK AT WHAT MAKES
rotate(shapeNum) {
OBJECT
ORIENTED // DEVELOPMENT IN *AVA SO MUCH FUN 7ELL LOOK AT THE DIFFERENCE BETWEEN // make the shape rotate 360º
A CLASS AND AN OBJECT 7ELL LOOK AT HOW OBJECTS CAN GIVE YOU A BETTER LIFE AT LEAST THE PROGRAM
}
MING PART OF YOUR LIFE .OT MUCH WE CAN DO ABOUT YOUR FASHION SENSE 7ARNING ONCE YOU GET playSound(shapeNum) {
// use shapeNum to lookup which }
TO /BJECTVILLE YOU MIGHT NEVER GO BACK 3END US A POSTCARD
// AIF sound to play, and play it
}
}
}
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... (AH 3O MUCH FOR THAT FOOFY // NONSENSE "UT THE SMIRK ON ,ARRYS FACE MELTED WHEN THE
2EALLY !NNOYING 0ROJECT -ANAGER SAID WITH THAT TONE OF DISAPPOINTMENT h/H NO THATS NOT
But wait! There’s been a spec change. HOW THE AMOEBA IS SUPPOSED TO ROTATEv
h/+ TECHNICALLY YOU WERE l RST ,ARRYv SAID THE -ANAGER hBUT WE HAVE TO ADD JUST ONE 4URNS OUT BOTH PROGRAMMERS HAD WRITTEN THEIR ROTATE CODE LIKE THIS
TINY THING TO THE PROGRAM )TLL BE NO PROBLEM FOR CRACK PROGRAMMERS LIKE YOU TWOv 1) determine the rectangle that surrounds the shape
h)F ) HAD A DIME FOR EVERY TIME )VE HEARD THAT ONEv THOUGHT ,ARRY KNOWING THAT SPEC
2) calculate the center of that rectangle, and rotate the shape around that point.
CHANGE
NO
PROBLEM WAS A FANTASY h!ND YET "RAD LOOKS STRANGELY SERENE 7HATS UP WITH "UT THE AMOEBA SHAPE WAS SUPPOSED TO ROTATE AROUND A POINT ON ONE END LIKE A CLOCK HAND
THATv 3TILL ,ARRY HELD TIGHT TO HIS CORE BELIEF THAT THE // WAY WHILE CUTE WAS JUST
SLOW !ND THAT IF YOU WANTED TO CHANGE HIS MIND YOUD HAVE TO PRY IT FROM HIS COLD h)M TOASTv THOUGHT ,ARRY VISUALIZING CHARRED 7ONDERBREAD© h!LTHOUGH HMMMM ) COULD
DEAD CARPAL
TUNNELLED HANDS JUST ADD ANOTHER IFELSE TO THE ROTATE PROCEDURE AND THEN JUST HARD
CODE THE ROTATION POINT
CODE FOR THE AMOEBA 4HAT PROBABLY WONT BREAK ANYTHINGv "UT THE LITTLE VOICE AT THE BACK OF
ape HIS HEAD SAID h"IG -ISTAKE $O YOU HONESTLY THINK THE SPEC WONT CHANGE AGAINv
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
4HE ROTATE PROCEDURE WOULD STILL WORK THE CODE USED "RAD SMILED SIPPED HIS MARGARITA AND WROTE ONE (E l GURED HE BETTER ADD ROTATION POINT ARGUMENTS chair at the Telluride Bluegrass Festival
A LOOKUP TABLE TO MATCH A SHAPE.UM TO AN ACTUAL NEW CLASS 3OMETIMES THE THING HE LOVED MOST TO THE ROTATE PROCEDURE ! LOT OF CODE WAS AFFECTED 7ITHOUT MISSING A BEAT "RAD MODIl ED THE ROTATE
SHAPE GRAPHIC "UT PLAY3OUND WOULD HAVE TO CHANGE ABOUT // WAS THAT HE DIDNT HAVE TO TOUCH CODE 4ESTING RECOMPILING THE WHOLE NINE YARDS ALL OVER METHOD BUT ONLY IN THE !MOEBA CLASS (E NEVER
!ND WHAT THE HECK IS A HIF l LE HED ALREADY TESTED AND DELIVERED h&LEXIBILITY AGAIN 4HINGS THAT USED TO WORK DIDNT TOUCHED THE TESTED WORKING
playSound(shapeNum) { EXTENSIBILITYv HE MUSED REm ECTING ON THE rotate(shapeNum, xPt, yPt) { COMPILED CODE FOR THE OTHER Amoeba
// if the shape is not an amoeba, BENEl TS OF // PARTS OF THE PROGRAM 4O int xPoint
Amoeba // if the shape is not an amoeba,
// use shapeNum to lookup which GIVE THE !MOEBA A ROTA
int yPoint
// AIF sound to play, and play it // calculate the center point
rotate() { TION POINT HE ADDED AN rotate() {
// else // code to rotate an amoeba // based on a rectangle,
// play amoeba .hif sound
ATTRIBUTE THAT ALL !MOEBAS // code to rotate an amoeba
} // then rotate WOULD HAVE (E MODI
// using amoeba’s x and y
}
playSound() { // else l ED TESTED AND DELIVERED }
)T TURNED OUT NOT TO BE SUCH A BIG DEAL BUT IT STILL
// code to play the new // use the xPt and yPt as WIRELESSLY THE REVISED playSound() {
MADE HIM QUEASY TO TOUCH PREVIOUSLY
TESTED CODE /F // .hif file for an amoeba
// the rotation point offset PROGRAM DURING A SINGLE // code to play the new
ALL PEOPLE HE SHOULD KNOW THAT NO MATTER WHAT THE } // .hif file for an amoeba
PROJECT MANAGER SAYS THE SPEC ALWAYS CHANGES // and then rotate "ELA &LECK SET
}
}
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()?
.OT SO FAST ,ARRY FOUND A mAW IN "RADS APPROACH !ND ,!229 7ASNT THAT THE WHOLE PROBLEM HERE THAT THE AMOEBA SHAPE
SINCE HE WAS SURE THAT IF HE GOT THE CHAIR HED ALSO GET ,UCY HAD A COMPLETELY DIFFERENT ROTATE AND PLAY3OUND PROCEDURE
IN ACCOUNTING HE HAD TO TURN THIS THING AROUND "2!$ -ETHOD ve
rride Now
O
,!229 9OUVE GOT DUPLICATED CODE 4HE ROTATE ,!229 7HATEVER (OW CAN AMOEBA DO SOMETHING DIFFERENT IF
PROCEDURE IS IN ALL FOUR 3HAPE THINGS As w
IT hINHERITSv ITS FUNCTIONALITY FROM THE 3HAPE CLASS k Me Ho
"2!$ )TS A METHOD NOT A PROCEDURE !ND THEYRE CLASSES "2!$ 4HATS THE LAST STEP 4HE !MOEBA CLASS OVERRIDES THE
NOT THINGS METHODS OF THE 3HAPE CLASS 4HEN AT RUNTIME THE *6- KNOWS EXACTLY
,!229 7HATEVER )TS A STUPID DESIGN 9OU HAVE TO WHICH ROTATE METHOD TO RUN WHEN SOMEONE TELLS THE !MOEBA TO ROTATE
MAINTAIN FOUR DIFFERENT ROTATE hMETHODSv (OW CAN THAT
EVER BE GOOD
"2!$ /H ) GUESS YOU DIDNT SEE THE lNAL DESIGN ,ET ME superclass Shape 4
(more abstract)
SHOW YOU HOW // INHERITANCE WORKS ,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 (OW DO YOU hTELLv AN !MOEBA TO
rotate() 3 care of myself.
common features and put them into a playSound() DO SOMETHING $ONT YOU HAVE TO CALL THE I know how an Amoeba
new class called Shape. PROCEDURE SORRYMETHOD AND THEN TELL IT I know how a Shape is is supposed to rotate
Shape Then I linked the other WHICH THING TO ROTATE and play a sound.
supposed to behave. Your
superclass four shape classes to job is to tell me what to
rotate() "2!$ 4HATS THE REALLY COOL THING ABOUT //
playSound() the new Shape class, do, and my job is to make it happen.
7HEN ITS TIME FOR SAY THE TRIANGLE TO ROTATE Don’t you worry your little program-
in a relationship called THE PROGRAM CODE INVOKES CALLS THE ROTATE mer head about how I do it.
inheritance. METHOD ON THE TRIANGLE OBJECT 4HE REST OF THE
You can read this as, “Square inherits from Shape”,
PROGRAM REALLY DOESNT KNOW OR CARE HOW THE
“Circle inherits from Shape”, and so on. I removed subclasses
rotate() and playSound() from the other shapes, so now
TRIANGLE DOES IT !ND WHEN YOU NEED TO ADD
there’s only one copy to maintain. SOMETHING NEW TO THE PROGRAM YOU JUST WRITE
Square Circle Triangle Amoeba A NEW CLASS FOR THE NEW OBJECT TYPE SO THE NEW
The Shape class is called the superclass of the other four
OBJECTS WILL HAVE THEIR OWN BEHAVIOR
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:
N things the object knows
!MY FROM THE SECOND m OOR
N things the object does
UNBEKNOWNST TO ALL THE 0ROJECT
-ANAGER HAD GIVEN THE SPEC TO Button Alarm
ShoppingCart
THREE PROGRAMMERS
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
4IME TO PUMP SOME NEURONS
“It helps me design in a more natural way. Things 9OU JUST READ A STORY BOUT A PROCEDURAL
have a way of evolving.” PROGRAMMER GOING HEAD
TO
HEAD WITH AN //
PROGRAMMER 9OU GOT A QUICK OVERVIEW OF SOME Things an object knows about itself are called Song
-Joy, 27, software architect
KEY // CONCEPTS INCLUDING CLASSES METHODS AND instance
ATTRIBUTES 7ELL SPEND THE REST OF THE CHAPTER N instance variables title knows
LOOKING AT CLASSES AND OBJECTS WELL RETURN TO variables artist
“Not messing around with code I’ve already
tested, just to add a new feature.” INHERITANCE AND OVERRIDING IN LATER CHAPTERS (state)
setTitle()
-Brad, 32, programmer "ASED ON WHAT YOUVE SEEN SO FAR AND WHAT YOU Things an object can do are called methods setArtist() does
MAY KNOW FROM A PREVIOUS // LANGUAGE YOUVE (behavior) play()
WORKED WITH TAKE A MOMENT TO THINK ABOUT N methods
“I like that the data and the methods that oper-
THESE QUESTIONS
ate on that data are together in one class.”
-Josh, 22, beer drinker 7HAT ARE THE FUNDAMENTAL THINGS YOU NEED TO
THINK ABOUT WHEN YOU DESIGN A *AVA CLASS 7HAT
“Reusing code in other applications. When I write ARE THE QUESTIONS YOU NEED TO ASK YOURSELF 4HINGS AN OBJECT KNOWS ABOUT ITSELF ARE CALLED INSTANCE Sharpen your pencil
a new class, I can make it flexible enough to be )F YOU COULD DESIGN A CHECKLIST TO USE WHEN VARIABLES 4HEY REPRESENT AN OBJECTS STATE THE DATA AND
used in something new, later.” YOURE DESIGNING A CLASS WHAT WOULD BE ON THE
-Chris, 39, project manager
CAN HAVE UNIQUE VALUES FOR EACH OBJECT OF THAT TYPE &ILL IN WHAT A TELEVISION OBJECT
CHECKLIST MIGHT NEED TO KNOW AND DO
Think of instance as another way of saying object.
“I can’t believe Chris just said that. He hasn’t 4HINGS AN OBJECT CAN DO ARE CALLED METHODS 7HEN YOU
written a line of code in 5 years.” DESIGN A CLASS YOU THINK ABOUT THE DATA AN OBJECT WILL NEED
-Daryl, 44, works for Chris metacognitive tip TO KNOW ABOUT ITSELF AND YOU ALSO DESIGN THE METHODS
THAT OPERATE ON THAT DATA )TS COMMON FOR AN OBJECT TO
If you’re stuck on an exercise, try talking about HAVE METHODS THAT READ OR WRITE THE VALUES OF THE INSTANCE
“Besides the chair?”
it out loud. Speaking (and hearing) activates VARIABLES &OR EXAMPLE !LARM OBJECTS HAVE AN INSTANCE
-Amy, 34, programmer
a different part of your brain. Although it VARIABLE TO HOLD THE ALARM4IME AND TWO METHODS FOR
works best if you have another person to
GETTING AND SETTING THE ALARM4IME
discuss it with, pets work too. That’s how
our dog learned polymorphism. 3O OBJECTS HAVE INSTANCE VARIABLES AND METHODS BUT THOSE
INSTANCE VARIABLES AND METHODS ARE DESIGNED AS PART OF THE
CLASS
void playIt() {
System.out.println(“Playing the movie”);
} The t wo uses of main:
}
N to test your real class
public class MovieTestDrive {
N to launch/start your Java application
public static void main(String[] args) {
Movie one = new Movie(); ! REAL *AVA APPLICATION IS NOTHING BUT OBJECTS TALKING TO OTHER OBJECTS )N THIS
one.title = “Gone with the Stock”; CASE TALKING MEANS OBJECTS CALLING METHODS ON ONE ANOTHER /N THE PREVIOUS
one.genre = “Tragic”; PAGE AND IN CHAPTER WE LOOK AT USING A MAIN METHOD FROM A SEPARATE
one.rating = -2; 4EST$RIVE CLASS TO CREATE AND TEST THE METHODS AND VARIABLES OF ANOTHER CLASS )N
Movie two = new Movie(); CHAPTER WE LOOK AT USING A CLASS WITH A MAIN METHOD TO START THE BALL ROLLING
two.title = “Lost in Cubicle Space”;
ON A REAL *AVA APPLICATION BY MAKING OBJECTS AND THEN TURNING THOSE OBJECTS
two.genre = “Comedy”; GameLauncher
LOOSE TO INTERACT WITH OTHER OBJECTS ETC
two.rating = 5; make
two.playIt(); !S A @SNEAK PREVIEW THOUGH OF HOW A REAL *AVA APPLICATION MIGHT BEHAVE GuessGs a
Movie three = new Movie(); HERES A LITTLE EXAMPLE "ECAUSE WERE STILL AT THE EARLIEST STAGES OF LEARNING *AVA obje ame
three.title = “Byte Club”; WERE WORKING WITH A SMALL TOOLKIT SO YOULL l ND THIS PROGRAM A LITTLE CLUNKY main(String[] args) tells citt and
three.genre = “Tragic but ultimately uplifting”; AND INEFl CIENT 9OU MIGHT WANT TO THINK ABOUT WHAT YOU COULD DO TO IMPROVE startG to
three.rating = 127; IT AND IN LATER CHAPTERS THATS EXACTLY WHAT WELL DO $ONT WORRY IF SOME OF THE ame
} CODE IS CONFUSING THE KEY POINT OF THIS EXAMPLE IS THAT OBJECTS TALK TO OBJECTS
}
Sharpen your pencil The Guessing Game GuessGame
instan
3UMMARY p1 variab ce
title 4HE GUESSING GAME INVOLVES A @GAME OBJECT AND THREE @PLAYER OBJECTS 4HE GAME GEN
p2 fortheles
MOVIE p3
genre ERATES A RANDOM NUMBER BETWEEN AND AND THE THREE PLAYER OBJECTS TRY TO GUESS players three
title object 1
IT 7E DIDNT SAY IT WAS A REALLY EXCITING GAME
genre rating startGame()
rating #LASSES
playIt() GuessGame.class Player.class GameLauncher.class
title the
4HE -OVIE4EST$RIVE CLASS CREATES OBJECTS INSTANCES OF object 2 genre 4HE ,OGIC Player this number
THE -OVIE CLASS AND USES THE DOT OPERATOR TO SET THE
guessepdlayer
rating 4HE 'AME,AUNCHER CLASS IS WHERE THE APPLICATION STARTS IT HAS THE MAIN METHOD number
INSTANCE VARIABLES TO A SPECIFIC VALUE 4HE -OVIE4EST$RIVE
CLASS ALSO INVOKES CALLS A METHOD ON ONE OF THE OBJECTS )N THE MAIN METHOD A 'UESS'AME OBJECT IS CREATED AND ITS START'AME METHOD
&ILL IN THE CHART TO THE RIGHT WITH THE VALUES THE THREE IS CALLED guess() meth
title makin od for
OBJECTS HAVE AT THE END OF MAIN
4HE 'UESS'AME OBJECTS START'AME METHOD IS WHERE THE ENTIRE GAME PLAYS OUT g u e ss g a
object 3 genre
)T CREATES THREE PLAYERS THEN hTHINKSv OF A RANDOM NUMBER THE TARGET FOR THE PLAYERS
rating TO GUESS )T THEN ASKS EACH PLAYER TO GUESS CHECKS THE RESULT AND EITHER PRINTS OUT
INFORMATION ABOUT THE WINNING PLAYERS OR ASKS THEM TO GUESS AGAIN
there are no
Dumb Questions
1dQ^OU_Q "% THE COMPILER
Q: 7HAT IF ) NEED GLOBAL Q: 7HAT IS A *AVA PROGRAM
VARIABLES AND METHODS (OW 7HAT DO YOU ACTUALLY DELIVER Each of the Java files on this page
DO ) DO THAT IF EVERYTHING HAS TO represents a complete source file.
GO IN A CLASS
Your job is to play compiler and
A: ! *AVA PROGRAM IS A PILE
OF CLASSES OR AT LEAST ONE CLASS
Make it Stic determine whether each of
A: 4HERE ISNT A CONCEPT OF )N A *AVA APPLICATION ONE OF
k these files will compile.
@GLOBAL VARIABLES AND METHODS IN THE CLASSES MUST HAVE A MAIN If they won’t compile,
! CLASS IS L
A *AVA // PROGRAM )N PRACTICAL METHOD USED TO START
UP THE IKE A RECIPE
how would you fix them,
USE HOWEVER THERE ARE TIMES PROGRAM 3O AS A PROGRAMMER /BJEC TS A
RE LIKE
WHEN YOU WANT A METHOD OR YOU WRITE ONE OR MORE CLASSES COOKIES and if they do compile,
A CONSTANT TO BE AVAILABLE !ND THOSE CLASSES ARE WHAT YOU what would be their output?
TO ANY CODE RUNNING IN ANY DELIVER )F THE END
USER DOESNT
PART OF YOUR PROGRAM 4HINK HAVE A *6- THEN YOULL ALSO
OF THE random() METHOD IN NEED TO INCLUDE THAT WITH
THE 0HRASE
/
-ATIC APP ITS A YOUR APPLICATIONS CLASSES A
METHOD THAT SHOULD BE C ALLABLE SO THAT THEY CAN RUN YOUR
class TapeDeck {
FROM ANYWHERE /R WHAT ABOUT PROGRAM 4HERE ARE A NUMBER
A CONSTANT LIKE PI 9OULL LEARN OF INSTALLER PROGRAMS THAT
IN CHAPTER THAT MARKING LET YOU BUNDLE YOUR CLASSES boolean canRecord = false; B
A METHOD AS public AND WITH A VARIETY OF *6-S SAY FOR
class DVDPlayer {
static MAKES IT BEHAVE MUCH DIFFERENT PLATFORMS AND PUT IT ALL
LIKE A @GLOBAL !NY CODE IN ANY ON A #$
2/- 4HEN THE END
USER BULLET POINTS void playTape() {
CLASS OF YOUR APPLICATION CAN CAN INSTALL THE CORRECT VERSION OF System.out.println(“tape playing”); boolean canRecord = false;
THE *6- ASSUMING THEY DONT
ß Object-oriented programming lets you extend
ACCESS A PUBLIC STATIC METHOD
a program without having to touch previously- }
!ND IF YOU MARK A VARIABLE AS ALREADY HAVE IT ON THEIR MACHINE
public static AND final tested, working code. void recordDVD() {
n YOU HAVE ESSENTIALLY MADE A ß All Java code is defined in a class. void recordTape() { System.out.println(“DVD recording”);
GLOBALLY
AVAILABLE CONSTANT A class describes how to make an object of System.out.println(“tape recording”);
Q: 7HAT IF ) HAVE A HUNDRED ß }
CLASSES /R A THOUSAND )SNT that class type. A class is like a blueprint. } }
THAT A BIG PAIN TO DELIVER ß An object can take care of itself; you don’t }
Q: 4HEN HOW IS THIS OBJECT
ALL THOSE INDIVIDUAL l LES have to know or care how the object does it.
ORIENTED IF YOU CAN STILL MAKE #AN ) BUNDLE THEM INTO ONE class DVDPlayerTestDrive {
ß An object knows things and does things.
GLOBAL FUNCTIONS AND GLOBAL !PPLICATION 4HING 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 IT WOULD BE A BIG of an object. DVDPlayer d = new DVDPlayer();
A: &IRST OF ALL EVERYTHING PAIN TO DELIVER A HUGE BUNCH OF ß Things an object does are called methods. t.canRecord = true; d.canRecord = true;
IN *AVA GOES IN A CLASS 3O THE INDIVIDUAL FILES TO YOUR END
USERS They represent the behavior of an object. t.playTape(); d.playDVD();
CONSTANT FOR PI AND THE METHOD BUT YOU WONT HAVE TO 9OU CAN
FOR random() ALTHOUGH BOTH PUT ALL OF YOUR APPLICATION FILES ß When you create a class, you may also want
PUBLIC AND STATIC ARE DEFINED INTO A *AVA !RCHIVE n A JAR FILE n to create a separate test class which you’ll if (t.canRecord == true) { if (d.canRecord == true) {
WITHIN THE Math CLASS !ND YOU THATS BASED ON THE PKZIP FORMAT use to create objects of your new class type. t.recordTape(); d.recordDVD();
MUST KEEP IN MIND THAT THESE )N THE JAR FILE YOU CAN INCLUDE ß A class can inherit instance variables and
STATIC GLOBAL
LIKE THINGS ARE THE A SIMPLE TEXT FILE FORMATTED AS } }
methods from a more abstract superclass.
EXCEPTION RATHER THAN THE RULE SOMETHING CALLED A MANIFEST THAT
IN *AVA 4HEY REPRESENT A VERY DEFINES WHICH CLASS IN THAT JAR ß At runtime, a Java program is nothing more } }
SPECIAL CASE WHERE YOU DONT HOLDS THE MAIN METHOD THAT than objects ‘talking’ to other objects.
} }
HAVE MULTIPLE INSTANCESOBJECTS SHOULD RUN
10
class ____________ {
if (d.s int _________ = 0;
nare == true
) {
d.playSn void ___________ {
are(); "ONUS 1UESTION
} System.out.println(“helloooo... “);
)F THE LAST LINE OF OUTPUT WAS }
INSTEAD OF HOW WOULD }
YOU COMPLETE THE PUZZLE
d.snare = false;
.OTE %ACH SNIPPET
class DrumKitTestDrive { FROM THE POOL CAN BE
USED MORE THAN ONCE
X X
();
TopHat Y X %CHO
d.play
E X 4ESTER
class DrumKit { ECHO
COUNT X E E
E E COUNT %CHO E
E COUNT HELLO %CHO E E
void playTopH
at () { %CHO E NEW %CHO X
ECOUNT COUNT
System.out.p X
rintln(“ding ECOUNT ECOUNT
File Edit Window Help Dance
ding da-ding”
} );
% java DrumKitTestDrive
bang bang ba-bang
ding ding da-ding
Be the Compiler:
! BUNCH OF *AVA COMPONENTS IN FULL COSTUME ARE PLAYING A PARTY
GAME h7HO AM )v 4HEY GIVE YOU A CLUE AND YOU TRY TO GUESS WHO 1dQ^OU_Q class TapeDeck {
THEY ARE BASED ON WHAT THEY SAY !SSUME THEY ALWAYS TELL THE TRUTH boolean canRecord = false;
ABOUT THEMSELVES )F THEY HAPPEN TO SAY SOMETHING THAT COULD BE TRUE %XERCISE 3OLUTIONS void playTape() {
FOR MORE THAN ONE OF THEM CHOOSE ALL FOR WHOM THAT SENTENCE CAN
APPLY &ILL IN THE BLANKS NEXT TO THE SENTENCE WITH THE NAMES OF ONE OR
System.out.println(“tape playing”);
MORE ATTENDEES 4HE FIRST ONES ON US A }
void recordTape() {
I?
am 4ONIGHTS ATTENDEES
System.out.println(“tape recording”);
Who #LASS -ETHOD /BJECT )NSTANCE VARIABLE }
}
0UZZLE 3OLUTIONS
Pool Puzzle
public class EchoTestDrive {
public static void main(String [] args) { 7HO AM )
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.
Serious Polymorphism
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?
What does a new Animal() object The compiler won’t let you instantiate
look like? an abstract class
!N ABSTRACT CLASS MEANS THAT NOBODY CAN EVER MAKE A NEW
INSTANCE OF THAT CLASS 9OU CAN STILL USE THAT ABSTRACT CLASS AS A
DECLARED REFERENCE TYPE FOR THE PURPOSE OF POLYMORPHISM BUT
YOU DONT HAVE TO WORRY ABOUT SOMEBODY MAKING OBJECTS OF THAT
TYPE 4HE COMPILER GUARANTEES IT
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. }
% java AnimalTestDrive
Animal added at 0
Animal added at 1
What about non-Animals? Why not make So what’s in this ultra-super-megaclass Object?
a class generic enough to take anything? )F YOU WERE *AVA WHAT BEHAVIOR WOULD YOU WANT EVERY
OBJECT TO HAVE (MMMM LETS SEE HOW ABOUT A Object
9OU KNOW WHERE THIS IS HEADING 7E WANT TO CHANGE THE a few of the METHOD THAT LETS YOU l ND OUT IF ONE OBJECT IS EQUAL
TYPE OF THE ARRAY ALONG WITH THE ADD METHOD ARGUMENT TO E RSI O
(These are just yList...there
Ar ra TO ANOTHER OBJECT 7HAT ABOUT A METHOD THAT CAN boolean equals()
V
N
methods in
SOMETHING ABOVE !NIMAL 3OMETHING EVEN MORE GENERIC MORE 3 TELL YOU THE ACTUAL CLASS TYPE OF THAT OBJECT -AYBE A Class getClass() the methods
are many more.) METHOD THAT GIVES YOU A HASHCODE FOR THE OBJECT SO
ABSTRACT THAN !NIMAL "UT HOW CAN WE DO IT 7E DONT HAVE A int hashCode() Just SOME of .
SUPERCLASS FOR !NIMAL YOU CAN USE THE OBJECT IN HASHTABLES WELL TALK ABOUT of clas s Obje ct
String toString()
*AVAS HASHTABLES IN CHAPTER AND APPENDIX "
4HEN AGAIN MAYBE WE DO
!RRAY,IST /H HERES A GOOD ONEA METHOD THAT PRINTS OUT A
2EMEMBER THOSE METHODS OF !RRAY,IST 3TRING MESSAGE FOR THAT OBJECT
,OOK HOW THE REMOVE CONTAINS AND YourClassHere Every class you write inherits all the
INDEX/F METHOD ALL USE AN OBJECT OF TYPE LEM !ND WHAT DO YOU KNOW !S IF BY MAGIC CLASS /BJECT
/BJECT DOES INDEED HAVE METHODS FOR THOSE FOUR THINGS
OVE/BJECT E DEX PARAMETER 2ETURNS methods of class Object. The classes
BOOLEAN REM JEC T AT THE IN
OB
2EMOVES THE THE LIST 4HATS NOT ALL THOUGH BUT THESE ARE THE ONES WE
you’ve written inherited methods you
LEMENT WAS IN
Every class in Java extends @TRUE IF THE E REALLY CARE ABOUT didn’t even know you had.
class Object. LEM R
AINS/BJECT E CT PARAMETE
1 equals(Object o)
BOOLEAN CONT F THERES A MATCH FOR THE OBJE
2ETURNS @T RU E I
#LASS /BJECT IS THE MOTHER OF ALL CLASSES ITS 3 hashCode()
THE SUPERCLASS OF EVERYTHING PTY Dog a = new Dog();
BOOLEAN IS%M ELEMENTS Cat c = new Cat(); Cat c = new Cat();
%VEN IF YOU TAKE ADVANTAGE OF POLYMORPHISM F T HE LIST HAS NO System.out.println(c.hashCode());
2ETURNS @TRUE I
YOU STILL HAVE TO CREATE A CLASS WITH METHODS if (a.equals(c)) {
BJECT ELEM RAMETER OR
File Edit Window Help Drop
THAT TAKE AND RETURN YOUR POLYMORPHIC TYPE INT INDEX/F/ ER THE INDEX OF THE OBJECT PA System.out.println(“true”); shcode
7ITHOUT A COMMON SUPERCLASS FOR EVERYTHING 2ETURNS EITH } else { % java TestObject Prints out a ha (for
IN *AVA THERED BE NO WAY FOR THE DEVELOPERS NDEX System.out.println(“false”);
ECT GETINT I ION IN THE LIST
/BJ
for the object as a
POSIT } 8202111
OF *AVA TO CREATE CLASSES WITH METHODS THAT EMENT AT THIS now, think of it
2ETURNS THE EL
COULD TAKE YOUR CUSTOM TYPES TYPES THEY NEVER File Edit Window Help Stop unique ID).
BJECT ELEM
KNEW ABOUT WHEN THEY WROTE THE !RRAY,IST CLASS BO OLEAN ADD/ T RETURNS @TRUE
ENT TO THE LIS % java TestObject
!DDS THE ELEM
3O YOU WERE MAKING SUBCLASSES OF CLASS /BJECT Tells you if two objects are
FROM THE VERY BEGINNING AND YOU DIDNT EVEN MORE false considered ‘equal’ (we’ll talk
KNOW IT %VERY CLASS YOU WRITE EXTENDS /BJECT about what ‘equal’ really 4 toString()
WITHOUT YOUR EVER HAVING TO SAY IT "UT YOU CAN means in appendix B). Cat c = new Cat();
THINK OF IT AS THOUGH A CLASS YOU WRITE LOOKS LIKE 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
"UT WAIT A MINUTE $OG ALREADY EXTENDS SOMETHING #ANINE thods can take anyt 2 getClass()
4HATS /+ 4HE COMPILER WILL MAKE #ANINE EXTEND /BJECT these ArrayList me ) Cat c = new Cat(); Cat@7d277f
INSTEAD %XCEPT #ANINE EXTENDS !NIMAL .O PROBLEM THEN THE , the get() and add( System.out.println(c.getClass());
(Note: as of Java 5.0k a little different
COMPILER WILL JUST MAKE !NIMAL EXTEND /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 $OG EXTENDS #ANINE IT DOESNT DIRECTLY EXTEND /BJECT class Cat and some other t.
the full story a lit instantiated from.
ALTHOUGH IT DOES EXTEND IT INDIRECTLY AND THE SAME IS TRUE rarely care abou
FOR #ANINE BUT !NIMAL DOES DIRECTLY EXTEND /BJECT
208 chapter 8 you are here4 209
Object and abstract classes interfaces and polymorphism
there are no
Dumb Questions Q: /+ BACK TO CLASS /BJECT Q: )F ITS SO GOOD TO USE Using polymorphic references of type Object has a price...
BEING NON
ABSTRACT SO ) GUESS POLYMORPHIC TYPES WHY
Q: )S CLASS /BJECT ABSTRACT THAT MEANS ITS CONCRETE (/7 DONT YOU JUST MAKE !,, YOUR "EFORE YOU RUN OFF AND START USING TYPE /BJECT FOR ALL YOUR ULTRA
m EXIBLE ARGUMENT AND RETURN
CAN YOU LET SOMEBODY MAKE AN METHODS TAKE AND RETURN TYPE TYPES YOU NEED TO CONSIDER A LITTLE ISSUE OF USING TYPE /BJECT AS A REFERENCE !ND KEEP IN MIND
/BJECT OBJECT )SNT THAT JUST /BJECT THAT WERE NOT TALKING ABOUT MAKING INSTANCES OF TYPE /BJECT WERE TALKING ABOUT MAKING
A: .O 7ELL NOT IN THE FORMAL AS WEIRD AS MAKING AN !NIMAL
*AVA SENSE ANYWAY /BJECT IS A INSTANCES OF SOME OTHER TYPE BUT USING A REFERENCE OF TYPE /BJECT
NON
ABSTRACT CLASS BECAUSE ITS OBJECT
A: !HHHH THINK ABOUT WHAT 7HEN YOU PUT AN OBJECT INTO AN !RRAY,IST$OG IT GOES IN AS A $OG AND COMES OUT AS A $OG
GOT METHOD IMPLEMENTATION WOULD HAPPEN &OR ONE THING
CODE THAT ALL CLASSES CAN INHERIT A: 'OOD QUESTION 7HY IS YOU WOULD DEFEAT THE WHOLE Make an ArrayList declared
AND USE OUT
OF
THE
BOX WITHOUT IT ACCEPTABLE TO MAKE A NEW POINT OF @TYPE
SAFETY ONE ArrayList<Dog> myDogArrayList = new ArrayList<Dog>();
to hold Dog objects.
HAVING TO OVERRIDE THE METHODS /BJECT INSTANCE "ECAUSE OF *AVAS GREATEST PROTECTION Dog aDog = new Dog(); Make a Dog.
SOMETIMES YOU JUST WANT A MECHANISMS FOR YOUR CODE 7ITH
TYPE
SAFETY *AVA GUARANTEES THAT myDogArrayList.add(aDog); Add the Dog to the list. able.
GENERIC OBJECT TO USE AS WELL AS to a new Dog reference vari
Q: 4HEN CAN YOU OVERRIDE AN OBJECT ! LIGHTWEIGHT OBJECT YOU WONT ASK THE WRONG OBJECT Dog d = myDogArrayList.get(0);
Assign the Dog from the listget() method declares a Dog return
the
THE METHODS IN /BJECT "Y FAR THE MOST COMMON USE OF TO DO SOMETHING YOU MEANT TO (Think of it as though ist<Dog>.)
AN INSTANCE OF TYPE /BJECT IS FOR ASK OF ANOTHER OBJECT TYPE ,IKE type because you used ArrayL
THREAD SYNCHRONIZATION WHICH ASK A &ERRARI WHICH YOU THINK IS A "UT WHAT HAPPENS WHEN YOU DECLARE IT AS !RRAY,IST/BJECT )F YOU WANT TO MAKE AN !RRAY,IST
A: 3OME OF THEM "UT SOME OF YOULL LEARN ABOUT IN CHAPTER 4OASTER TO COOK ITSELF THAT WILL LITERALLY TAKE ANY KIND OF /BJECT YOU DECLARE IT LIKE THIS
THEM ARE MARKED final WHICH &OR NOW JUST STICK THAT ON THE "UT THE TRUTH IS YOU DONT HAVE
MEANS YOU CANT OVERRIDE THEM BACK BURNER AND ASSUME THAT TO WORRY ABOUT THAT FIERY &ERRARI Make an ArrayList declared
9OURE ENCOURAGED STRONGLY TO YOU WILL RARELY MAKE OBJECTS OF SCENARIO EVEN IF YOU DO USE ArrayList<Object> myDogArrayList = new ArrayList<Object>();
to hold any type of Object.
OVERRIDE HASH#ODE EQUALS TYPE /BJECT EVEN THOUGH YOU /BJECT REFERENCES FOR EVERYTHING Dog aDog = new Dog();
AND TO3TRING IN YOUR OWN "ECAUSE WHEN OBJECTS ARE
Make a Dog. (These two steps are the same.)
CAN
CLASSES AND YOULL LEARN HOW TO REFERRED TO BY AN /BJECT myDogArrayList.add(aDog); Add the Dog to the list.
DO THAT A LITTLE LATER IN THE BOOK REFERENCE TYPE *AVA THINKS ITS
"UT SOME OF THE METHODS LIKE Q: 3O IS IT FAIR TO SAY THAT THE REFERRING TO AN INSTANCE OF TYPE "UT WHAT HAPPENS WHEN YOU TRY TO GET THE $OG OBJECT AND ASSIGN IT TO A $OG REFERENCE
GET#LASS DO THINGS THAT MUST MAIN PURPOSE FOR TYPE /BJECT /BJECT !ND THAT MEANS THE
WORK IN A SPECIFIC GUARANTEED IS SO THAT YOU CAN USE IT FOR A ONLY METHODS YOURE ALLOWED TO NO!! Won’t compile!! When you use ArrayList<Object>, the get() method
myD
m
Dog d = myDogArrayList.get(0);
WAY POLYMORPHIC ARGUMENT AND CALL ON THAT OBJECT ARE THE ONES returns type Object. The Compiler knows only that the object inherits from
RETURN TYPE ,IKE IN !RRAY,IST DECLARED IN CLASS /BJECT 3O IF Object (somewhere in its inheritance tree) but it doesn’t know it’s a Dog !!
YOU WERE TO SAY
Q: )F !RRAY,IST METHODS ARE %VERYTHING COMES OUT OF AN !RRAY,IST/BJECT AS A REFERENCE OF TYPE /BJECT REGARDLESS OF WHAT THE
GENERIC ENOUGH TO USE /BJECT A: 4HE /BJECT CLASS SERVES Object o = new Ferrari(); ACTUAL OBJECT IS OR WHAT THE REFERENCE TYPE WAS WHEN YOU ADDED THE OBJECT TO THE LIST
THEN WHAT DOES IT MEAN TO SAY TWO MAIN PURPOSES TO ACT AS A o.goFast(); //Not legal!
!RRAY,IST$OT#OM ) THOUGHT POLYMORPHIC TYPE FOR METHODS
) WAS RESTRICTING THE !RRAY,IST TO THAT NEED TO WORK ON ANY CLASS 9OU WOULDNT EVEN MAKE IT PAST
HOLD ONLY $OT#OM OBJECTS THAT YOU OR ANYONE ELSE MAKES THE COMPILER The objects go IN
AND TO PROVIDE REAL METHOD CODE Objects come out of
as SoccerBall,
THAT ALL OBJECTS IN *AVA NEED AT "ECAUSE *AVA IS A STRONGLY
TYPED
A: 9OU WERE RESTRICTING IT RUNTIME AND PUTTING THEM IN Fish, Guitar, and an ArrayList<Object>
LANGUAGE THE COMPILER CHECKS
0RIOR TO *AVA !RRAY,ISTS CLASS /BJECT MEANS ALL OTHER Car. acting like they’re
TO MAKE SURE THAT YOURE CALLING
COULDNT BE RESTRICTED 4HEY CLASSES INHERIT THEM 3OME OF generic instances
A METHOD ON AN OBJECT THATS
WERE ALL ESSENTIALLY WHAT YOU THE MOST IMPORTANT METHODS IN ACTUALLY CAPABLE OF RESPONDING of class Object. The
GET IN *AVA TODAY IF YOU WRITE /BJECT ARE RELATED TO THREADS )N OTHER WORDS YOU CAN CALL A ArrayList<Object> Compiler cannot
!RRAY,IST/BJECT )N OTHER AND WELL SEE THOSE LATER IN THE METHOD ON AN OBJECT REFERENCE assume the object
WORDS AN !RRAY,IST RESTRICTED BOOK ONLY IF THE CLASS OF THE REFERENCE But they come
TO ANYTHING THATS AN /BJECT that comes out is of
TYPE ACTUALLY HAS THE METHOD
WHICH MEANS ANY OBJECT IN *AVA OUT as though any type other than
7ELL COVER THIS IN MUCH GREATER
INSTANTIATED FROM ANY CLASS TYPE they were of type
DETAIL A LITTLE LATER SO DONT WORRY Object.
7ELL COVER THE DETAILS OF THIS NEW
IF THE PICTURE ISNT CRYSTAL CLEAR Object. Object Object Object Object
TYPE SYNTAX LATER IN THE BOOK
When a Dog won’t act like a Dog I don’t know what you’re Objects don’t bark.
talking about. Sit? Stay?
4HE PROBLEM WITH HAVING EVERYTHING TREATED bark? Hmmmm... I don’t 3O NOW WE KNOW THAT WHEN AN OBJECT IS
POLYMORPHICALLY AS AN /BJECT IS THAT THE OBJECTS recall knowing those. REFERENCED BY A VARIABLE DECLARED AS TYPE
APPEAR TO LOSE BUT NOT PERMANENTLY THEIR /BJECT IT CANT BE ASSIGNED TO A VARIABLE
TRUE ESSENCE 4HE $OG APPEARS TO LOSE ITS DOGNESS
o
DECLARED WITH THE ACTUAL OBJECTS TYPE
,ETS SEE WHAT HAPPENS WHEN WE PASS A $OG TO t
!ND WE KNOW THAT THIS CAN HAPPEN WHEN D og
objec
Object
A METHOD THAT RETURNS A REFERENCE TO THE SAME A RETURN TYPE OR ARGUMENT IS DECLARED
$OG OBJECT BUT DECLARES THE RETURN TYPE AS TYPE AS TYPE /BJECT AS WOULD BE THE CASE
/BJECT RATHER THAN $OG FOR EXAMPLE WHEN THE OBJECT IS PUT When you get an object reference from
INTO AN !RRAY,IST OF TYPE /BJECT USING
!RRAY,IST/BJECT "UT WHAT ARE THE
an ArrayList<Object> (or any method
IMPLICATIONS OF THIS )S IT A PROBLEM TO that declares Object as the return type),
method HAVE TO USE AN /BJECT REFERENCE VARIABLE it comes back as a polymorphic reference
public void go() { though the e TO REFER TO A $OG OBJECT ,ETS TRY TO CALL type of Object. So you have an Object
lin e w on ’t work! Eventhe very same Dog tht
to bj ec $OG METHODS ON OUR $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
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
)F A REFERENCE IS LIKE A REMOTE CONTROL THE
Object, regardless of
REMOTE CONTROL TAKES ON MORE AND MORE BUTTONS the type it was when
AS YOU MOVE DOWN THE INHERITANCE TREE ! you put it in.
REMOTE CONTROL REFERENCE OF TYPE /BJECT HAS
ONLY A FEW BUTTONSTHE BUTTONS FOR THE EXPOSED When you get a
METHODS OF CLASS /BJECT "UT A REMOTE CONTROL reference from an
OF TYPE 3NOWBOARD INCLUDES ALL THE BUTTONS FROM ArrayList<Object>, the
Get in touch with your inner Object. CLASS /BJECT PLUS ANY NEW BUTTONS FOR NEW reference is always of
METHODS OF CLASS 3NOWBOARD 4HE MORE SPECIlC
!N OBJECT CONTAINS EVERYTHING IT INHERITS FROM EACH OF ITS type Object.
THE CLASS THE MORE BUTTONS IT MAY HAVE
SUPERCLASSES 4HAT MEANS EVERY OBJECTREGARDLESS OF ITS
ACTUAL CLASS TYPEIS ALSO AN INSTANCE OF CLASS /BJECT4HAT /F COURSE THATS NOT ALWAYS TRUE A SUBCLASS MIGHT That means you get an
MEANS ANY OBJECT IN *AVA CAN BE TREATED NOT JUST AS A $OG NOT ADD ANY NEW METHODS BUT SIMPLY OVERRIDE Object remote control.
"UTTON OR 3NOWBOARD BUT ALSO AS AN /BJECT 7HEN YOU THE METHODS OF ITS SUPERCLASS 4HE KEY POINT IS
SAY new Snowboard() YOU GET A SINGLE OBJECT ON THE THAT EVEN IF THE OBJECT IS OF TYPE 3NOWBOARD AN
HEAPA 3NOWBOARD OBJECTBUT THAT 3NOWBOARD WRAPS /BJECT REFERENCE TO THE 3NOWBOARD OBJECT CANT SEE
ITSELF AROUND AN INNER CORE REPRESENTING THE /BJECT THE 3NOWBOARD
SPECIlC METHODS
CAPITAL h/v PORTION OF ITSELF
Object
)
equals() A single object d( turn
re
)
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
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