Headfirst Java 2 ND Edition
Headfirst Java 2 ND Edition
Dedication.............................................................................................................................. 2
What they're saying about Head First..................................................................................... 3
Praise for Head First Java............................................................................................................................................................................................................... 3
Praise for other Head First books co-authored by Kathy and Bert................................................................................................................................................ 3
Other related books from O'Reilly.................................................................................................................................................................................................. 3
Intro....................................................................................................................................... 7
Who is this book for?....................................................................................................................................................................................................................... 7
We know what you're thinking........................................................................................................................................................................................................ 7
And we know what your brain is thinking...................................................................................................................................................................................... 7
Metacognition: thinking about thinking......................................................................................................................................................................................... 7
Here's what WE did:........................................................................................................................................................................................................................ 7
Here's what YOU can do to bend your brain into submission........................................................................................................................................................ 7
What you need for this book:.......................................................................................................................................................................................................... 7
Last-minute things you need to know:............................................................................................................................................................................................ 7
Technical Editors............................................................................................................................................................................................................................. 7
Other people to credit:..................................................................................................................................................................................................................... 7
Just when you thought there wouldn't be any more acknowledgements....................................................................................................................................... 7
Chapter 1. Breaking the Surface............................................................................................ 19
Section 1.1. The Way Java Works.................................................................................................................................................................................................. 20
Section 1.2. What you'll do in Java................................................................................................................................................................................................ 21
Section 1.3. A very brief history of Java........................................................................................................................................................................................ 22
Section 1.4. Sharpen your pencil................................................................................................................................................................................................... 23
Section 1.5. Sharpen your pencil answers..................................................................................................................................................................................... 24
Section 1.6. Code structure in Java............................................................................................................................................................................................... 25
Section 1.7. Anatomy of a class...................................................................................................................................................................................................... 26
Section 1.8. Writing a class with a main........................................................................................................................................................................................ 27
Section 1.9. What can you say in the main method?.................................................................................................................................................................... 28
Section 1.10. Looping and looping and......................................................................................................................................................................................... 29
Section 1.11. there are no Dumb Questions.................................................................................................................................................................................. 30
Section 1.12. Conditional branching.............................................................................................................................................................................................. 31
Section 1.13. Coding a Serious Business Application.................................................................................................................................................................... 32
Section 1.14. Monday morning at Bob's........................................................................................................................................................................................ 33
Section 1.15. Phrase-O-Matic........................................................................................................................................................................................................ 35
Section 1.16. Fireside Chats........................................................................................................................................................................................................... 36
Section 1.17. Exercise: Code Magnets........................................................................................................................................................................................... 38
Section 1.18. Exercise: BE The compiler....................................................................................................................................................................................... 39
Section 1.19. JavaCross 7.0........................................................................................................................................................................................................... 40
Section 1.20. Mixed Messages....................................................................................................................................................................................................... 41
Section 1.21. Pool Puzzle................................................................................................................................................................................................................ 42
Section 1.22. Exercise Solutins: Code Magnets:........................................................................................................................................................................... 43
Chapter 2. A Trip to Objectville............................................................................................. 45
Section 2.1. Chair Wars................................................................................................................................................................................................................. 46
Section 2.2. Brain Power................................................................................................................................................................................................................ 51
Section 2.3. Making your first object............................................................................................................................................................................................ 54
Section 2.4. Making and testing Movie objects............................................................................................................................................................................. 55
Section 2.5. Quick! Get out of main!............................................................................................................................................................................................. 56
Section 2.6. Running the Guessing Game..................................................................................................................................................................................... 58
Section 2.7. Who am I?.................................................................................................................................................................................................................. 63
Chapter 3. Know Your Variables........................................................................................... 67
Section 3.1. Declaring a variable................................................................................................................................................................................................... 68
Section 3.2. "I'd like a double mocha, no, make it an int."........................................................................................................................................................... 69
Section 3.3. You really don't want to spill that............................................................................................................................................................................. 70
Section 3.4. Back away from that keyword!.................................................................................................................................................................................. 71
Section 3.5. This table reserved..................................................................................................................................................................................................... 71
Section 3.6. Controlling your Dog object...................................................................................................................................................................................... 72
Section 3.7. An object reference is just another variable value.................................................................................................................................................... 73
Section 3.8. There are no Dumb Question.................................................................................................................................................................................... 74
Section 3.9. Java Exposed............................................................................................................................................................................................................. 74
Section 3.10. Life on the garbage-collectible heap........................................................................................................................................................................ 75
Section 3.11. Life and death on the heap....................................................................................................................................................................................... 76
Section 3.12. An array is like a tray of cups................................................................................................................................................................................... 77
Section 3.13. Arrays are objects too............................................................................................................................................................................................... 77
Section 3.14. Make an array of Dogs............................................................................................................................................................................................. 78
Section 3.15. Control your Dog...................................................................................................................................................................................................... 79
Section 3.16. A Dog example......................................................................................................................................................................................................... 80
Section 3.17. Exercise: BE the compiler........................................................................................................................................................................................ 81
Section 3.18. Exercise: Code Magnets........................................................................................................................................................................................... 82
Section 3.19. Pool Puzzle............................................................................................................................................................................................................... 83
Section 3.20. A Heap o' Trouble................................................................................................................................................................................................... 84
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Section 3.21. Five-Minute Mystery............................................................................................................................................................................................... 85
Section 3.22. Exercise Solutions: Code Magnets.......................................................................................................................................................................... 86
Section 3.23. Puzzle Solutions....................................................................................................................................................................................................... 87
Chapter 4. How Objects Behave............................................................................................ 89
Section 4.1. Remember: a class describes what an object knows and what an object does........................................................................................................ 90
Section 4.2. The size affects the bark............................................................................................................................................................................................. 91
Section 4.3. You can send things to a method.............................................................................................................................................................................. 92
Section 4.4. You can get things back from a method.................................................................................................................................................................... 93
Section 4.5. You can send more than one thing to a method....................................................................................................................................................... 94
Section 4.6. there are no Dumb Questions................................................................................................................................................................................... 96
Section 4.7. Reminder: Java cares about type!............................................................................................................................................................................. 96
Section 4.8. Cool things you can do with parameters and return types....................................................................................................................................... 97
Section 4.9. Encapsulation............................................................................................................................................................................................................ 98
Section 4.10. Encapsulating the GoodDog class......................................................................................................................................................................... 100
Section 4.11. How do objects in an array behave?....................................................................................................................................................................... 101
Section 4.12. Declaring and initializing instance variables........................................................................................................................................................ 102
Section 4.13. The difference between instance and local variables............................................................................................................................................ 103
Section 4.14. there are no Dumb Questions................................................................................................................................................................................ 103
Section 4.15. Comparing variables (primitives or references).................................................................................................................................................... 104
Section 4.16. Exercise: BE the compiler...................................................................................................................................................................................... 106
Section 4.17. Who am I?............................................................................................................................................................................................................... 107
Section 4.18. Mixed Messages..................................................................................................................................................................................................... 108
Section 4.19. Pool Puzzle............................................................................................................................................................................................................. 109
Section 4.20. Five Minute Mystery.............................................................................................................................................................................................. 110
Section 4.21. Puzzle Solutions...................................................................................................................................................................................................... 112
Chapter 5. Extra-Strength Methods..................................................................................... 113
Section 5.1. Let's build a Battleship-style game: "Sink a Dot Com"............................................................................................................................................ 114
Section 5.2. First, a high-level design.......................................................................................................................................................................................... 115
Section 5.3. The "Simple Dot Com Game" a gentler introduction.............................................................................................................................................. 116
Section 5.4. Developing a Class.................................................................................................................................................................................................... 117
Section 5.5. BRAIN POWER........................................................................................................................................................................................................ 117
Section 5.6. There are no Dumb Questions................................................................................................................................................................................. 121
Section 5.7. There are no Dumb Questions................................................................................................................................................................................. 124
Section 5.8. Exercise: BE the JVM.............................................................................................................................................................................................. 136
Section 5.9. Exercise: Code Magnets........................................................................................................................................................................................... 137
Section 5.10. Java Cross............................................................................................................................................................................................................... 138
Section 5.11. Exercise Solutions................................................................................................................................................................................................... 140
Chapter 6. Using the Java Library....................................................................................... 143
Section 6.1. In our last chapter, we left you with the cliff-hanger. A bug................................................................................................................................... 144
Section 6.2. So what happened?.................................................................................................................................................................................................. 145
Section 6.3. How do we fix it?...................................................................................................................................................................................................... 146
Section 6.4. Option one is too clunky.......................................................................................................................................................................................... 147
Section 6.5. Option two is a little better, but still pretty clunky................................................................................................................................................. 147
Section 6.6. Wake up and smell the library................................................................................................................................................................................. 150
Section 6.7. Some things you can do with ArrayList................................................................................................................................................................... 151
Section 6.8. there are no Dumb Questions.................................................................................................................................................................................. 153
Section 6.9. Java Exposed............................................................................................................................................................................................................ 153
Section 6.10. Comparing ArrayList to a regular array................................................................................................................................................................ 154
Section 6.11. Comparing ArrayList to a regular array................................................................................................................................................................. 155
Section 6.12. Let's fix the DotCom code...................................................................................................................................................................................... 156
Section 6.13. New and improved DotCom class.......................................................................................................................................................................... 157
Section 6.14. Let's build the REAL game: "Sink a Dot Com"...................................................................................................................................................... 158
Section 6.15. What needs to change?........................................................................................................................................................................................... 159
Section 6.16. Who does what in the DotComBust game (and when)......................................................................................................................................... 160
Section 6.17. Prep code for the real DotComBust class............................................................................................................................................................... 162
Section 6.18. The final version of the Dotcom class.................................................................................................................................................................... 168
Section 6.19. Super Powerful Boolean Expressions.................................................................................................................................................................... 169
Section 6.20. Ready-bake Code................................................................................................................................................................................................... 170
Section 6.21. Ready-bake Code.................................................................................................................................................................................................... 171
Section 6.22. Using the Library (the Java API)........................................................................................................................................................................... 172
Section 6.23. You have to know the full name of the class you want to use in your code.......................................................................................................... 173
Section 6.24. there are no Dumb Questions................................................................................................................................................................................ 173
Section 6.25. there are no Dumb Questions................................................................................................................................................................................ 175
Section 6.26. How to play with the API....................................................................................................................................................................................... 176
Section 6.27. Code Magnets......................................................................................................................................................................................................... 179
Section 6.28. JavaCross 7.0......................................................................................................................................................................................................... 180
Section 6.29. Exercise Solutions.................................................................................................................................................................................................. 181
Section 6.30. JavaCross answers................................................................................................................................................................................................. 182
Chapter 7. Better Living in Objectville................................................................................. 183
Section 7.1. Chair Wars Revisited................................................................................................................................................................................................ 184
Section 7.2. BRAIN POWER........................................................................................................................................................................................................ 185
Section 7.3. there are no Dumb Questions.................................................................................................................................................................................. 194
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Section 7.4. there are no Dumb Questions.................................................................................................................................................................................. 198
Section 7.5. brain power.............................................................................................................................................................................................................. 206
Section 7.6. there are no Dumb Questions................................................................................................................................................................................. 207
Section 7.7. Exercise: Mixed Messages....................................................................................................................................................................................... 210
Section 7.8. Exercise BE the Compiler......................................................................................................................................................................................... 211
Section 7.9. Exercise Solutions: BE the Compiler....................................................................................................................................................................... 213
Chapter 8. Serious Polymorphism....................................................................................... 215
Section 8.1. Did we forget about something when we designed this?........................................................................................................................................ 216
Section 8.2. BRAIN POWER....................................................................................................................................................................................................... 220
Section 8.3. there are no Dumb Questions................................................................................................................................................................................. 243
Section 8.4. Pool Puzzle.............................................................................................................................................................................................................. 250
Section 8.5. Exercise Solutions.................................................................................................................................................................................................... 251
Chapter 9. Life and Death of an Object................................................................................ 253
Section 9.1. The Stack and the Heap: where things live............................................................................................................................................................. 254
Section 9.2. Methods are stacked................................................................................................................................................................................................ 255
Section 9.3. What about local variables that are objects?.......................................................................................................................................................... 256
Section 9.4. there are no Dumb Questions................................................................................................................................................................................. 256
Section 9.5. If local variables live on the stack, where do instance variables live?.................................................................................................................... 257
Section 9.6. The miracle of object creation................................................................................................................................................................................. 258
Section 9.7. Construct a Duck..................................................................................................................................................................................................... 260
Section 9.8. Initializing the state of a new Duck......................................................................................................................................................................... 261
Section 9.9. there are no Dumb Questions.................................................................................................................................................................................. 261
Section 9.10. Using the constructor to initialize important Duck state..................................................................................................................................... 262
Section 9.11. Make it easy to make a Duck.................................................................................................................................................................................. 263
Section 9.12. Doesn't the compiler always make a no-arg constructor for you? No!................................................................................................................. 264
Section 9.13. there are no Dumb Questions................................................................................................................................................................................ 266
Section 9.14. there are no Dumb Questions................................................................................................................................................................................ 267
Section 9.15. Wait a minute... we never DID talk about superclasses and inheritance and how that all fits in with constructors.......................................... 268
Section 9.16. Making a Hippo means making the Animal and Object parts too....................................................................................................................... 270
Section 9.17. How do you invoke a superclass constructor?....................................................................................................................................................... 271
Section 9.18. Can the child exist before the parents?................................................................................................................................................................. 272
Section 9.19. Superclass constructors with arguments............................................................................................................................................................... 273
Section 9.20. Invoking one overloaded constructor from another............................................................................................................................................ 274
Section 9.21. Now we know how an object is born, but how long does an object live?............................................................................................................. 276
Section 9.22. What about reference variables?........................................................................................................................................................................... 278
Chapter 10. Numbers Matter............................................................................................... 291
Section 10.1. MATH methods: as close as you'll ever get to a global method............................................................................................................................ 292
Section 10.2. The difference between regular (non-static) and static methods......................................................................................................................... 293
Section 10.3. What it means to have a class with static methods............................................................................................................................................... 294
Section 10.4. Static methods can't use non-static (instance) variables!.................................................................................................................................... 295
Section 10.5. Static methods can't use non-static methods, either!........................................................................................................................................... 296
Section 10.6. Static variable: value is the same for ALL instances of the class.......................................................................................................................... 297
Section 10.7. Initializing a static variable................................................................................................................................................................................... 299
Section 10.8. static final variables are constants........................................................................................................................................................................ 300
Section 10.9. final isn't just for static variables........................................................................................................................................................................... 301
Section 10.10. there are no Dumb Questions............................................................................................................................................................................. 302
Section 10.11. Math methods...................................................................................................................................................................................................... 304
Section 10.12. Wrapping a primitive........................................................................................................................................................................................... 305
Section 10.13. Before Java 5.0, YOU had to do the work........................................................................................................................................................... 306
Section 10.14. Autoboxing: blurring the line bet ween primitive and object............................................................................................................................. 307
Section 10.15. Autoboxing works almost everywhere................................................................................................................................................................ 308
Section 10.16. But wait! There's more! Wrappers have static utility methods too!................................................................................................................... 310
Section 10.17. And now in reverse... turning a primitive number into a String.......................................................................................................................... 311
Section 10.18. Number formatting.............................................................................................................................................................................................. 312
Section 10.19. Formatting deconstructed.................................................................................................................................................................................... 313
Section 10.20. The percent (%) says, "insert argument here" (and format it using these instructions)................................................................................... 314
Section 10.21. The format String uses its own little language syntax......................................................................................................................................... 315
Section 10.22. The format specifier............................................................................................................................................................................................. 316
Section 10.23. The only required specifier is for TYPE............................................................................................................................................................... 317
Section 10.24. What happens if I have more than one argument?............................................................................................................................................. 318
Section 10.25. So much for numbers, what about dates?........................................................................................................................................................... 319
Section 10.26. Working with Dates............................................................................................................................................................................................. 320
Section 10.27. Moving backward and for ward in time............................................................................................................................................................... 321
Section 10.28. Getting an object that extends Calendar............................................................................................................................................................. 322
Section 10.29. Working with Calendar objects........................................................................................................................................................................... 323
Section 10.30. Highlights of the Calendar API........................................................................................................................................................................... 324
Section 10.31. Even more Statics!... static imports..................................................................................................................................................................... 325
Section 10.32. Lunar Code Magnets........................................................................................................................................................................................... 330
Chapter 11. Risky Behavior.................................................................................................. 333
Section 11.1. Let's make a Music Machine................................................................................................................................................................................... 334
Section 11.2. We'll start with the basics....................................................................................................................................................................................... 335
Section 11.3. First we need a Sequencer...................................................................................................................................................................................... 336
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Section 11.4. Something's wrong!................................................................................................................................................................................................ 336
Section 11.5. What happens when a method you want to call (probably in a class you didn't write) is risky?......................................................................... 337
Section 11.6. Methods in Java use exceptions to tell the calling code, "Some thing Bad Happened. I failed."......................................................................... 338
Section 11.7. The compiler needs to know that YOU know you're calling a risky method........................................................................................................ 339
Section 11.8. An exception is an object of type Exception....................................................................................................................................................... 340
Section 11.9. If it's your code that catches the exception, then whose code throws it?.............................................................................................................. 341
Section 11.10. there are no Dumb Questions.............................................................................................................................................................................. 342
Section 11.11. Flow control in try/catch blocks........................................................................................................................................................................... 344
Section 11.12. Finally: for the things you want to do no matter what........................................................................................................................................ 345
Section 11.13. Sharpen your pencil:Flow Control....................................................................................................................................................................... 346
Section 11.14. Did we mention that a method can throw more than one exception?................................................................................................................ 347
Section 11.15. Exceptions are polymorphic................................................................................................................................................................................. 348
Section 11.16. Multiple catch blocks must be ordered from smallest to biggest........................................................................................................................ 350
Section 11.17. You can't put bigger baskets above smaller baskets............................................................................................................................................. 351
Section 11.18. Sharpen your pencil.............................................................................................................................................................................................. 352
Section 11.19. When you don't want to handle an exception................................................................................................................................................... 353
Section 11.20. Ducking (by declaring) only delays the inevitable.............................................................................................................................................. 354
Section 11.21. Getting back to our music code......................................................................................................................................................................... 356
Section 11.22. Code Kitchen......................................................................................................................................................................................................... 357
Section 11.23. Making actual sound............................................................................................................................................................................................ 358
Section 11.24. Your very first sound player app.......................................................................................................................................................................... 360
Section 11.25. Making a MidiEvent (song data).......................................................................................................................................................................... 361
Section 11.26. MIDI message: the heart of a MidiEvent............................................................................................................................................................. 362
Section 11.27. Anatomy of a message.......................................................................................................................................................................................... 362
Section 11.28. Version 2: Using command-line args to experiment with sounds...................................................................................................................... 364
Section 11.29. Exercise: True or False......................................................................................................................................................................................... 366
Section 11.30. Exercise: Code Magnets....................................................................................................................................................................................... 367
Section 11.31. JavaCross 7.0........................................................................................................................................................................................................ 368
Section 11.32. Exercise Solutions: True or False........................................................................................................................................................................ 369
Section 11.33. Code Magnets....................................................................................................................................................................................................... 369
Section 11.34. JavaCross Answers............................................................................................................................................................................................... 370
Chapter 12. A Very Graphic.................................................................................................. 371
Section 12.1. It all starts with a window...................................................................................................................................................................................... 372
Section 12.2. Your first GUI: a button on a frame...................................................................................................................................................................... 373
Section 12.3. Getting a user event............................................................................................................................................................................................... 375
Section 12.4. Getting a button's ActionEvent............................................................................................................................................................................. 378
Section 12.5. There are no Dumb Questions.............................................................................................................................................................................. 380
Section 12.6. Make your own drawing widget............................................................................................................................................................................ 382
Section 12.7. Because life's too short to paint the circle a solid color when there's a gradient blend waiting for you.............................................................. 385
Section 12.8. BULLET POINTS.................................................................................................................................................................................................. 386
Section 12.9. We can get an event............................................................................................................................................................................................... 387
Section 12.10. Let's try it with TWO buttons.............................................................................................................................................................................. 390
Section 12.11. Java Exposed: This weeks interview: Instance of an Inner Class....................................................................................................................... 398
Section 12.12. There are no Dumb Questions............................................................................................................................................................................. 400
Section 12.13. Code Kitchen........................................................................................................................................................................................................ 404
Section 12.14. Exercise: Who am I?............................................................................................................................................................................................. 412
Section 12.15. Exercise: BE the compiler..................................................................................................................................................................................... 413
Section 12.16. Pool Puzzle............................................................................................................................................................................................................ 414
Section 12.17. Exercise Solutions: Who am I?............................................................................................................................................................................. 415
Section 12.18. Pool Puzzle............................................................................................................................................................................................................ 416
Chapter 13. Work on Your Swing......................................................................................... 417
Section 13.1. Swing components.................................................................................................................................................................................................. 418
Section 13.2. Layout Managers.................................................................................................................................................................................................... 419
Section 13.3. How does the layout manager decide?.................................................................................................................................................................. 420
Section 13.4. The Big Three layout managers: border, flow, and box........................................................................................................................................ 421
Section 13.5. there are no Dumb Questions................................................................................................................................................................................ 430
Section 13.6. Playing with Swing components............................................................................................................................................................................ 431
Section 13.7. there are no Dumb Questions................................................................................................................................................................................ 434
Section 13.8. Code Kitchen.......................................................................................................................................................................................................... 436
Section 13.9. Making the BeatBox............................................................................................................................................................................................... 437
Section 13.10. Exercise: Which code goes with which layout?................................................................................................................................................... 442
Section 13.11. Code Fragments.................................................................................................................................................................................................... 443
Chapter 14. Saving Objects.................................................................................................. 447
Section 14.1. Capture the Beat..................................................................................................................................................................................................... 448
Section 14.2. Saving State............................................................................................................................................................................................................ 449
Section 14.3. Writing a serialized object to a file........................................................................................................................................................................ 450
Section 14.4. Data moves in streams from one place to another................................................................................................................................................ 451
Section 14.5. What really happens to an object when it's serialized?......................................................................................................................................... 452
Section 14.6. But what exactly IS an object's state? What needs to be saved?........................................................................................................................... 453
Section 14.7. If you want your class to be serializable, implement Serializable......................................................................................................................... 455
Section 14.8. There are no Dumb Questions.............................................................................................................................................................................. 458
Section 14.9. Deserialization: restoring an object...................................................................................................................................................................... 459
Section 14.10. What happens during deserialization?............................................................................................................................................................... 460
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Section 14.11. There are no Dumb Questions.............................................................................................................................................................................. 461
Section 14.12. Saving and restoring the game characters........................................................................................................................................................... 462
Section 14.13. The GameCharacter class..................................................................................................................................................................................... 463
Section 14.14. Object Serialization.............................................................................................................................................................................................. 464
Section 14.15. Writing a String to a Text File.............................................................................................................................................................................. 465
Section 14.16. Text File Example: e-Flashcards.......................................................................................................................................................................... 466
Section 14.17. Quiz Card Builder (code outline)......................................................................................................................................................................... 467
Section 14.18. The java.io.File class............................................................................................................................................................................................ 470
Section 14.19. The beauty of buffers............................................................................................................................................................................................ 471
Section 14.20. Reading from a Text File..................................................................................................................................................................................... 472
Section 14.21. Quiz Card Player (code outline)........................................................................................................................................................................... 473
Section 14.22. Parsing with String split()................................................................................................................................................................................... 476
Section 14.23. There are no Dumb Questions............................................................................................................................................................................. 477
Section 14.24. Version ID: A Big Serialization Gotcha............................................................................................................................................................... 478
Section 14.25. Using the serialVersionUID................................................................................................................................................................................. 479
Section 14.26. Code Kitchen....................................................................................................................................................................................................... 480
Section 14.27. Saving a BeatBox pattern..................................................................................................................................................................................... 481
Section 14.28. Restoring a BeatBox pattern............................................................................................................................................................................... 482
Section 14.29. Sharpen your pencil: Can they be saved?........................................................................................................................................................... 483
Section 14.30. Exercise: True or False........................................................................................................................................................................................ 484
Section 14.31. Code Magnets....................................................................................................................................................................................................... 485
Section 14.32. Exercise Solutions............................................................................................................................................................................................... 486
Chapter 15. Make a Connection........................................................................................... 488
Section 15.1. Real-time Beat Box Chat........................................................................................................................................................................................ 489
Section 15.2. Connecting, Sending, and Receiving..................................................................................................................................................................... 491
Section 15.3. Make a network Socket connection....................................................................................................................................................................... 492
Section 15.4. A TCP port is just a number: A 16-bit number that identifies a specific program on the server......................................................................... 493
Section 15.5. To read data from a Socket, use a BufferedReader............................................................................................................................................... 495
Section 15.6. To write data to a Socket, use a PrintWriter......................................................................................................................................................... 496
Section 15.7. DailyAdviceClient code.......................................................................................................................................................................................... 498
Section 15.8. Writing a simple server......................................................................................................................................................................................... 500
Section 15.9. DailyAdviceServer code.......................................................................................................................................................................................... 501
Section 15.10. Writing a Chat Client........................................................................................................................................................................................... 503
Section 15.11. Java has multiple threads but only one Thread class.......................................................................................................................................... 507
Section 15.12. What does it mean to have more than one call stack?........................................................................................................................................ 508
Section 15.13. Every Thread needs a job to do: A method to put on the new thread stack........................................................................................................ 510
Section 15.14. To make a job for your thread, implement the Runnable interface..................................................................................................................... 511
Section 15.15. The Thread Scheduler........................................................................................................................................................................................... 514
Section 15.16. there are no Dumb Questions............................................................................................................................................................................... 517
Section 15.17. Putting a thread to sleep....................................................................................................................................................................................... 518
Section 15.18. Using sleep to make our program more predictable........................................................................................................................................... 519
Section 15.19. Making and starting two threads......................................................................................................................................................................... 520
Section 15.20. What will happen?............................................................................................................................................................................................... 520
Section 15.21. Um, yes. There IS a dark side. Threads can lead to concurrency 'issues'............................................................................................................ 521
Section 15.22. The Ryan and Monica problem, in code.............................................................................................................................................................. 523
Section 15.23. The Ryan and Monica example........................................................................................................................................................................... 524
Section 15.24. We need the makeWithdrawal ( ) method to run as one atomic thing............................................................................................................... 527
Section 15.25. Using an object's lock........................................................................................................................................................................................... 528
Section 15.26. The dreaded "Lost Update" problem................................................................................................................................................................... 529
Section 15.27. Let's run this code................................................................................................................................................................................................ 530
Section 15.28. Make the increment() method atomic. Synchronize it!...................................................................................................................................... 531
Section 15.29. there are no Dumb Questions.............................................................................................................................................................................. 531
Section 15.30. The deadly side of synchronization..................................................................................................................................................................... 533
Section 15.31. New and improved SimpleChatClient.................................................................................................................................................................. 535
Section 15.32. Ready-bake Code: The really really simple Chat Server..................................................................................................................................... 537
Section 15.33. there are no Dumb Questions.............................................................................................................................................................................. 539
Section 15.34. Code Kitchen........................................................................................................................................................................................................ 540
Section 15.35. Exercise: Code Magnets....................................................................................................................................................................................... 541
Section 15.36. Exercise Solutions................................................................................................................................................................................................ 543
Section 15.37. Five-Minute Mystery............................................................................................................................................................................................ 544
Chapter 16. Data structures................................................................................................ 546
Section 16.1. Tracking song popularity on your jukebox............................................................................................................................................................ 547
Section 16.2. Here's what you have so far, without the sort:...................................................................................................................................................... 548
Section 16.3. But the ArrayList class does NOT have a sort() method!..................................................................................................................................... 549
Section 16.4. ArrayList is not the only collection........................................................................................................................................................................ 550
Section 16.5. You could use a TreeSet... Or you could use the Collections.sort() method......................................................................................................... 551
Section 16.6. Adding Collections.sort() to the Jukebox code..................................................................................................................................................... 552
Section 16.7. But now you need Song objects, not just simple Strings....................................................................................................................................... 553
Section 16.8. Changing the Jukebox code to use Songs instead of Strings................................................................................................................................ 554
Section 16.9. It won't compile!.................................................................................................................................................................................................... 555
Section 16.10. The sort() method declaration............................................................................................................................................................................. 555
Section 16.11. Generics means more type-safety......................................................................................................................................................................... 557
Section 16.12. Learning generics................................................................................................................................................................................................. 558
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Section 16.13. Using generic CLASSES....................................................................................................................................................................................... 559
Section 16.14. Using type parameters with ArrayList................................................................................................................................................................. 560
Section 16.15. Using generic METHODS..................................................................................................................................................................................... 561
Section 16.16. Here's where it gets weird.................................................................................................................................................................................... 562
Section 16.17. Revisiting the sort() method................................................................................................................................................................................ 564
Section 16.18. In generics, "extends" means "extends or implements"...................................................................................................................................... 565
Section 16.19. Finally we know what's wrong............................................................................................................................................................................. 566
Section 16.20. The new, improved, comparable Song class....................................................................................................................................................... 567
Section 16.21. We can sort the list, but....................................................................................................................................................................................... 568
Section 16.22. Using a custom comparator................................................................................................................................................................................. 569
Section 16.23. Updating the Jukebox to use a Comparator........................................................................................................................................................ 570
Section 16.24. Sharpen your pencil: Reverse Engineer.............................................................................................................................................................. 570
Section 16.25. Sharpen your pencil: Fill-in-the-blanks.............................................................................................................................................................. 572
Section 16.26. Uh-oh. The sorting all works, but now we have duplicates................................................................................................................................ 573
Section 16.27. We need a Set instead of a List............................................................................................................................................................................ 574
Section 16.28. The Collection API (part of it)............................................................................................................................................................................. 575
Section 16.29. Using a HashSet instead of ArrayList.................................................................................................................................................................. 576
Section 16.30. What makes two objects equal?........................................................................................................................................................................... 577
Section 16.31. How a HashSet checks for duplicates: hashCode() and equals()........................................................................................................................ 578
Section 16.32. The Song class with overridden hashCode() and equals().................................................................................................................................. 579
Section 16.33. there are no Dumb Questions............................................................................................................................................................................. 580
Section 16.34. And if we want the set to stay sorted, we've got TreeSet..................................................................................................................................... 581
Section 16.35. What you MUST know about TreeSet................................................................................................................................................................. 582
Section 16.36. TreeSet elements MUST be comparable............................................................................................................................................................. 583
Section 16.37. We've seen Lists and Sets, now we'll use a Map.................................................................................................................................................. 584
Section 16.38. Finally, back to generics...................................................................................................................................................................................... 585
Section 16.39. Using polymorphic arguments and generics...................................................................................................................................................... 586
Section 16.40. But will it work with ArrayList<Dog> ?.............................................................................................................................................................. 587
Section 16.41. What could happen if it were allowed................................................................................................................................................................. 588
Section 16.42. Wildcards to the rescue........................................................................................................................................................................................ 591
Section 16.43. Alternate syntax for doing the same thing.......................................................................................................................................................... 592
Section 16.44. there are no Dumb Questions.............................................................................................................................................................................. 592
Section 16.45. Exercise: BE the compiler, advanced.................................................................................................................................................................. 593
Section 16.46. Solution to the "Reverse Engineer" sharpen exercise......................................................................................................................................... 594
Section 16.47. Exercise Solution.................................................................................................................................................................................................. 595
Section 16.48. BE the compiler solution..................................................................................................................................................................................... 596
Chapter 17. Release Your Code............................................................................................ 598
Section 17.1. Deploying your application.................................................................................................................................................................................... 599
Section 17.2. Imagine this scenario............................................................................................................................................................................................ 600
Section 17.3. Separate source code and class files...................................................................................................................................................................... 601
Section 17.4. Put your Java in a JAR.......................................................................................................................................................................................... 602
Section 17.5. Running (executing) the JAR................................................................................................................................................................................ 603
Section 17.6. Put your classes in packages!................................................................................................................................................................................ 604
Section 17.7. Preventing package name conflicts....................................................................................................................................................................... 605
Section 17.8. Compiling and running with packages.................................................................................................................................................................. 607
Section 17.9. The -d flag is even cooler then we said.................................................................................................................................................................. 608
Section 17.10. Making an executable JAR with packages.......................................................................................................................................................... 609
Section 17.11. So where did the manifest file go?........................................................................................................................................................................ 610
Section 17.12. Java Web Start...................................................................................................................................................................................................... 614
Section 17.13. The .jnlp file.......................................................................................................................................................................................................... 616
Section 17.14. Steps for making and deploying a Java Web Start app........................................................................................................................................ 617
Section 17.15. What's First?......................................................................................................................................................................................................... 618
Section 17.16. True or False......................................................................................................................................................................................................... 619
Section 17.17. Summary-Cross 7.0.............................................................................................................................................................................................. 620
Chapter 18. Distributed Computing.................................................................................... 624
Section 18.1. Method calls are always bet ween two objects on the same heap......................................................................................................................... 625
Section 18.2. What if you want to invoke a method on an object running on another machine?............................................................................................. 626
Section 18.3. Object A, running on Little, wants to call a method on Object B, running on Big............................................................................................... 627
Section 18.4. But you can't do that.............................................................................................................................................................................................. 627
Section 18.5. The role of the 'helpers'......................................................................................................................................................................................... 629
Section 18.6. Java RMI gives you the client and service helper objects!.................................................................................................................................... 631
Section 18.7. How does the client get the stub object?............................................................................................................................................................... 637
Section 18.8. How does the client get the stub class?................................................................................................................................................................. 638
Section 18.9. Be sure each machine has the class files it needs................................................................................................................................................. 639
Section 18.10. Sharpen your pencil: What's First?..................................................................................................................................................................... 640
Section 18.11. Yeah, but who really uses RMI?........................................................................................................................................................................... 641
Section 18.12. What about Servlets?........................................................................................................................................................................................... 642
Section 18.13. A very simple Ser vlet........................................................................................................................................................................................... 644
Section 18.14. HTML page with a link to this servlet................................................................................................................................................................. 644
Section 18.15. There are no Dumb Questions............................................................................................................................................................................. 645
Section 18.16. Just for fun, let's make the Phrase-O-Matic work as a servlet............................................................................................................................ 646
Section 18.17. Phrase-O-Matic code, servlet-friendly................................................................................................................................................................. 647
Section 18.18. Enterprise JavaBeans: RMI on steroids.............................................................................................................................................................. 648
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Section 18.19. For our final trick... a little Jini........................................................................................................................................................................... 649
Section 18.20. Adaptive discovery in action............................................................................................................................................................................... 650
Section 18.21. Self-healing net work in action............................................................................................................................................................................ 652
Section 18.22. Final Project: the Universal Service browser...................................................................................................................................................... 653
Section 18.23. How it works:....................................................................................................................................................................................................... 654
Section 18.24. The classes and interfaces:.................................................................................................................................................................................. 656
Section 18.25. Sharpen your pencil............................................................................................................................................................................................. 661
Section 18.26. Congratulations!.................................................................................................................................................................................................. 665
Appendix A. Final Code Kitchen.......................................................................................... 666
Section A.1. Final BeatBox client program.................................................................................................................................................................................. 667
Appendix B. The Top Ten Topics that almost made it into the Real Book............................. 676
Section B.1. #10 Bit Manipulation............................................................................................................................................................................................... 677
Section B.2. #9 Immutability...................................................................................................................................................................................................... 678
Section B.3. #8 Assertions........................................................................................................................................................................................................... 679
Section B.4. #7 Block Scope........................................................................................................................................................................................................ 680
Section B.5. #6 Linked Invocations............................................................................................................................................................................................. 681
Section B.6. #5 Anonymous and Static Nested Classes............................................................................................................................................................. 682
Section B.7. #5 Anonymous and Static Nested Classes, continued........................................................................................................................................... 683
Section B.8. #4 Access Levels and Access Modifiers (Who Sees What).................................................................................................................................... 684
Section B.9. #4 Access Levels and Access Modifiers, cont......................................................................................................................................................... 684
Section B.10. #3 String and StringBuffer/StringBuilder Methods............................................................................................................................................ 686
Section B.11. #2 Multidimensional Arrays.................................................................................................................................................................................. 687
Section B.12. And the number one topic that didn't quite make it in... #1 Enumerations (also called Enumerated Types or Enums).................................. 688
Section B.13. Using "if" and "switch" with Enums..................................................................................................................................................................... 689
Section B.14. #1 Enumerations, completed................................................................................................................................................................................ 690
Section B.15. Five-Minute Mystery: A Long Trip Home............................................................................................................................................................. 691
Section B.16. Five-Minute Mystery Solution.............................................................................................................................................................................. 692
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Head First Java
8econd Edition
ly Kaihy Siciia anu Bcii Baics
Coyiighi 200S, 200 ly O`Rcilly Mcuia, Inc. All iighis icscivcu.
Piinicu in ihc Uniicu Siaics ol Amciica.
Pullishcu ly O`Rcilly Mcuia, Inc., 100 Giavcnsicin Highway Noiih, Sclasiool, CA 9472.
O`Rcilly Mcuia looIs may lc uichascu loi cuucaiional, lusincss, oi salcs iomoiional usc.
Onlinc cuiiions aic also availallc loi mosi iiilcs salaii.oicilly.com). Ioi moic inloimaiion,
coniaci oui coioiaic/insiiiuiional salcs ucaiimcni: S00) 99S-99SS oi coioiaicCoicilly.com.
Editor: MiIc IouIiucs
Cover Designer: Euic Iiccuman
nterior Designers: Kaihy Siciia anu Bcii Baics
Printing History:
May 200S: Iiisi Euiiion.
Icliuaiy 200: Scconu Euiiion.
You mighi wani io icI u a coy ol boL cuiiions... loi youi Iius. ThinI cBay)
Thc O`Rcilly logo is a icgisicicu iiaucmaiI ol O`Rcilly Mcuia, Inc. ]ava anu all ]ava-lascu
iiaucmaiIs anu logos aic iiaucmaiIs oi icgisicicu iiaucmaiIs ol Sun Miciosysicms, Inc., in ihc
Uniicu Siaics anu oihci couniiics. O`Rcilly Mcuia, Inc. is inuccnucni ol Sun Miciosysicms.
Many ol ihc ucsignaiions uscu ly manulaciuicis anu scllcis io uisiinguish ihcii iouucis aic
claimcu as iiaucmaiIs.
Whcic ihosc ucsignaiions acai in ihis looI, anu O`Rcilly Mcuia, Inc. was awaic ol a iiaucmaiI
claim, ihc ucsignaiions havc lccn iinicu in cas oi iniiial cas.
Whilc cvciy iccauiion has lccn iaIcn in ihc icaiaiion ol ihis looI, ihc ullishci anu ihc
auihois assumc no icsonsililiiy loi ciiois oi omissions, oi loi uamagcs icsuliing liom ihc usc ol
ihc inloimaiion coniaincu hcicin.
In oihci woius, il you usc anyihing in HenJ E:. Jn.n io, say, iun a nuclcai owci lani oi aii
iialhc coniiol sysicm, you`ic on youi own.
ISBN: 09600920S
]M|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
To oui liains, loi always lcing ihcic
ucsiic shaIy cviucncc)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
What they're saying about Head First
]ava icchnology is cvciywhcic-Il you ucvclo soliwaic anu havcn`i lcaincu ]ava, ii`s uchniicly
iimc io uivc in-Hcau Iiisi."
- Scott McNcaly, Sun Microsystcms Chairman, Prcsidcnt and CEO
Bcyonu ihc cngaging siylc ihai uiags you loiwaiu liom Inow-noihing inio cxalicu ]ava waiiioi siaius,
Hcau Iiisi ]ava covcis a hugc amouni ol iaciical maiicis ihai oihci icxis lcavc as ihc uicaucu cxcicisc
loi ihc icauci..." Ii`s clcvci, wiy, hi anu iaciical-ihcic aicn`i a loi ol icxilooIs ihai can maIc ihai claim
anu livc u io ii whilc also icaching you aloui ol|cci sciializaiion anu nciwoiI launch ioiocols. "
- Dr. Dan Russcll, Dircctor oI Uscr Scicnccs and Expcricncc Rcscarch
IBM Almadcn Rcscarch Ccntcr (and tcachcs Artihcial Intclligcncc at StanIord Univcrsity)
Kaihy anu Bcii`s Hcau Iiisi ]ava` iiansloims ihc iinicu agc inio ihc closcsi ihing io a GUI you`vc
cvci sccn. In a wiy, hi mannci, ihc auihois maIc lcaining ]ava an cngaging whai`ic ihcy gonna uo
ncxi.` cxciicncc."
- Warrcn KcuIIcl, SoItwarc Dcvclopmcnt Magazinc
Ii`s lasi, iiicvcicni, lun, anu cngaging. Bc caiclul-you mighi aciually lcain somcihing!"
- Kcn Arnold, Iormcr Scnior Enginccr at Sun Microsystcms
Co-author (with ]amcs Gosling, crcator oI ]ava), Thc ]ava Programming Languagc
Amazon namcu Hcau Iiisi ]ava
a To Tcn Euiioi`s Choicc loi
Comuici BooIs ol 200S
hisi cuiiion)
Soliwaic Dcvclomcni Magazinc namcu
Hcau Iiisi ]ava a hnalisi loi ihc 14ih Annual
]oli Cola/Piouuci Exccllcncc Awaius
...ihc only way io ucciuc ihc woiih ol a iuioiial is io ucciuc how wcll ii icachcs. Hcau Iiisi ]ava cxccls ai
icaching. OK, I ihoughi ii was silly... ihcn I icalizcu ihai I was ihoioughly lcaining ihc ioics as I wcni
ihiough ihc looI."
Thc siylc ol Hcau Iiisi ]ava mauc lcaining, wcll, casici."
- slashdot (honcstpuck's rcvicw)
Hcau Iiisi ]ava is liIc Moniy Pyihon mccis ihc gang ol loui... ihc icxi is lioIcn u so wcll ly uzzlcs
anu sioiics, quizzcs anu cxamlcs, ihai you covci giounu liIc no comuici looI lcloic."
- Douglas Rowc, Columbia ]ava Uscrs Group
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Rcau Hcau Iiisi ]ava anu you will oncc again cxciicncc lun in lcaining...Ioi colc who liIc io lcain
ncw iogiamming languagcs, anu uo noi comc liom a comuici scicncc oi iogiamming lacIgiounu,
ihis looI is a gcm... This is onc looI ihai maIcs lcaining a comlcx comuici languagc lun. I hoc
ihai ihcic aic moic auihois who aic willing io licaI oui ol ihc samc olu molu ol iiauiiional` wiiiing
siylcs. Icaining comuici languagcs shoulu lc lun, noi oncious."
- ]udith Taylor, Southcast Ohio Macromcdia Uscr Group
A lcw uays ago I icccivcu my coy ol Hcau Iiisi ]ava ly Kaihy Siciia anu Bcii Baics. I`m only aii way
ihiough ihc looI, lui whai`s amazcu mc is ihai cvcn in my slcc-uciivcu siaic ihai hisi cvcning, I lounu
myscll ihinIing, OK, |usi onc moic agc, ihcn I`ll go io lcu.`
- ]oc Litton
Il you`ic iclaiivcly ncw io iogiamming anu you aic inicicsicu in ]ava, hcic`s youi looI...Covciing
cvciyihing liom ol|ccis io cicaiing giahical usci inicilaccs GUI), cxcciion ciioi) hanuling io nci-
woiIing socIcis) anu muliiihicauing, cvcn acIaging u youi ilc ol classcs inio onc insiallaiion hlc,
ihis looI is quiic comlcic...Il you liIc ihc siylc...I`m cciiain you`ll lovc ihc looI anu, liIc mc, hoc
ihai ihc Hcau Iiisi sciics will cxanu io many oihci sul|ccis!"
- LinuxQucstions.org
I was ADDICTED io ihc looI`s shoii sioiics, annoiaicu couc, mocI inicivicws, anu liain cxciciscs."
- Michacl Yuan, author, Entcrprisc ]2ME
Praise for Head First Java
Hcau Iiisi ]ava`... givcs ncw mcaning io ihcii maiIciing hiasc `Thcic`s an O Rcilly loi ihai.` I
icIcu ihis u lccausc scvcial oihcis I icscci hau ucsciilcu ii in icims liIc icvoluiionaiy` anu a
ucsciilcu a iauically uillcicni aioach io ihc icxilooI. Thcy wcic aic) iighi... In iyical O`Rcilly
lashion, ihcy`vc iaIcn a scicniihc anu wcll consiucicu aioach. Thc icsuli is lunny, iiicvcicni, ioical,
iniciaciivc, anu liilliani...Rcauing ihis looI is liIc siiiing in ihc scaIcis loungc ai a vicw conlcicncc,
lcaining liom - anu laughing wiih - ccis... Il you wani io UNDERSTAND ]ava, go luy ihis looI."
- Andrcw Pollack, www.thcnorth.com
Il you wani io ]ava, looI no luiihci: wclcomc io ihc hisi GUI-lascu icchnical looI! This
cilccily-cxccuicu, giounu-licaIing loimai uclivcis lcnchis oihci ]ava icxis simly can`i...
Picaic youiscll loi a iiuly icmaiIallc iiuc ihiough ]ava lanu."
- Ncil R. Bauman, Captain & CEO, Gcck Cruiscs (www.GcckCruiscs.com)
Il anyonc in ihc woilu is lamiliai wiih ihc concci ol Hcau Iiisi,` ii woulu lc mc. This
looI is so goou, I`u maiiy ii on TV!"
- Rick Rockwcll, Comcdian
Thc original FOX Tclcvision Who Wants to Marry a Millionairc groom
This siull is so liicIing goou ii maIcs mc wanna WEEP! I`m siunncu."
- Floyd ]oncs, Scnior Tcchnical Writcr/Poolboy, BEA
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
IINAIIY - a ]ava looI wiiiicn ihc way I woulu`a wioic ii il I wcic mc.
Sciiously ihough - ihis looI alsoluicly llows away cvciy oihci soliwaic looI I`vc cvci icau...
A goou looI is vciy uilhculi io wiiic... you havc io iaIc a loi ol iimc io maIc ihings unlolu in a
naiuial, icauci oiicnicu" scqucncc. Ii`s a loi ol woiI. Mosi auihois clcaily aicn`i u io ihc challcngc.
Congiaiulaiions io ihc Hcau Iiisi E]B icam loi a hisi class |ol!
- Wally Flint
I coulu noi havc imagincu a cison smiling whilc siuuying an IT looI! Using Hcau Iiisi E]B
maiciials, I goi a gicai scoic 91%) anu sci a woilu iccoiu as ihc youngcsi SCBCD, 14 ycais."
- AIsah ShaIquat (world's youngcst SCBCD)
Praise for other Head First books co-authored by Kathy and Bert
I lccl liIc a ihousanu ounus ol looIs havc |usi lccn lilicu oll ol my hcau."
- Ward Cunningham, invcntor oI thc Wiki
and Ioundcr oI thc Hillsidc Group
I laughcu, I ciicu, ii movcu mc."
- Dan Stcinbcrg, Editor-in-ChicI, java.nct
My hisi icaciion was io ioll on ihc uooi laughing. Alici I icIcu myscll u, I icalizcu ihai noi only is ihc
looI icchnically accuiaic, ii is ihc casicsi io unucisianu iniiouuciion io ucsign aiicins ihai I havc sccn."
- Dr. Timothy A. Budd, Associatc ProIcssor oI Computcr Scicncc at Orcgon Statc Univcrsity
author oI morc than a dozcn books including C++ [or ]ovo Progrommers
]usi ihc iighi ionc loi ihc gccIcu-oui, casual-cool guiu couci in all ol us. Thc iighi iclcicncc loi iac-
iical ucvclomcni siiaicgics-gcis my liain going wiihoui having io slog ihiough a lunch ol iiicu
sialc iolcssoi-scaI."
- Travis Kalanick, Foundcr oI Scour and Rcd Swoosh
Mcmbcr oI thc MIT TR100
This Hcau Iiisi Scivlcis looI is as goou as ihc Hcau Iiisi E]B looI, which mauc mc laugh
AND gavc mc 97% on ihc cxam!"
- ]cI Cumps, ]2EE consultant, Cronos
Amazon namcu Hcau Iiisi Scivlcis
a To Tcn Euiioi`s Choicc loi
Comuici BooIs ol 2004
hisi cuiiion)
Soliwaic Dcvclomcni Magazinc namcu
Hcau Iiisi Scivlcis anu Hcau Iiisi Dcsign
Paiicins hnalisis loi ihc 1ih Annual
Piouuci Exccllcncc Awaius
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Other related books from OReilly
Ant: The Defnitive Guide
Better, Faster, Lighter Java
Enterprise JavaBeans 3.0
Hibernate: A Developer's Notebook
Java 1.5 Tiger: A Developer's Notebook
Java Cookbook
Java in a Nutshell
Java Network Programming
Java Servlet & JSP Cookbook
Java Swing
JavaServer Faces
JavaServer Pages
Programming Jakarta Struts
Tomcat: The Definitive Guide
Other books in OReillys Head First series
Head First Java
Head First Object-Oriented Analysis and Design (OOA&D)
Head Rush Ajax
Head First HTML with CSS and XHTML
Head First Design Patterns
Head First EJB
Head First PMP
Head First SQL
Head First Software Development
Head First C#
Head First JavaScript
Head First Programming (2008)
Head First Ajax (2008)
Head First Physics (2008)
Head First Statistics (2008)
Head First Ruby on Rails (2008)
Head First PHP & MySQL (2008)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
xxi
8f8l 88f00ll
1a-a
spese3
] ge eomgj|e;
Dog
D
og ob
j
e
c
f
size
inf
lide
Dog
8ll P0lk5
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
the intro
you are here xxvii
So, wc uiu oui aii. Thc icsi is u io you. Thcsc iis aic a
siaiiing oini, Iisicn io youi liain anu hguic oui whai woiIs
loi you anu whai uocsn`i. Tiy ncw ihings.
Hcrcs whz! Y00 rzn 4e !e |cn4 yeer
|rz|n |n!e se|m|ss|en.
1
8low down. The more you understand,
the less you have to memorize.
Don`i |usi .enJ. Sio anu ihinI. Whcn ihc
looI asIs you a qucsiion, uon`i |usi sIi io
ihc answci. Imaginc ihai somconc ically .
asIing ihc qucsiion. Thc moic uccly you
loicc youi liain io ihinI, ihc lciici chancc
you havc ol lcaining anu icmcmlciing.
2
Do the exercises. Write your own notes.
Wc ui ihcm in, lui il wc uiu ihcm loi you,
ihai woulu lc liIc having somconc clsc
uo youi woiIouis loi you. Anu uon`i |usi
IooI ai ihc cxciciscs. Usc a pcncil. Thcic`s
lcniy ol cviucncc ihai hysical aciiviiy
whilc lcaining can incicasc ihc lcaining.
3
Read the There are No Dumb Ouestions
Thai mcans all ol ihcm. Thcy`ic noi
oiional siuc-lais-ihcy`ic aii ol ihc coic
conicni! Somciimcs ihc qucsiions aic moic
usclul ihan ihc answcis.
4
Don't do all your reading in one place.
Sianu-u, siicich, movc aiounu, changc
chaiis, changc iooms. Ii`ll hcl youi liain
eeI somcihing, anu Iccs youi lcaining liom
lcing ioo connccicu io a aiiiculai lacc.
5
Make this the last thing you read before
bed. Or at least the last challenging thing.
Paii ol ihc lcaining csccially ihc iianslci
io long-icim mcmoiy) hacns alici you ui
ihc looI uown. Youi liain nccus iimc on
iis own, io uo moic ioccssing. Il you ui in
somcihing ncw uuiing ihai ioccssing-iimc,
somc ol whai you |usi lcaincu will lc losi.
6
Drink water. Lots of it.
Youi liain woiIs lcsi in a nicc laih ol uuiu.
Dchyuiaiion which can hacn lcloic you
cvci lccl ihiisiy) uccicascs cogniiivc lunciion.
7
Talk about it. Out loud.
ScaIing aciivaics a uillcicni aii ol
ihc liain. Il you`ic iiying io unucisianu
somcihing, oi incicasc youi chancc ol
icmcmlciing ii laici, say ii oui louu. Bciici
siill, iiy io cxlain ii oui louu io somconc
clsc. You`ll lcain moic quicIly, anu you mighi
uncovci iucas you haun`i Inown wcic ihcic
whcn you wcic icauing aloui ii.
8
Listen to your brain.
Pay aiicniion io whcihci youi liain is gciiing
ovciloaucu. Il you hnu youiscll siaiiing io sIim
ihc suilacc oi loigci whai you |usi icau, ii`s
iimc loi a licaI. Oncc you go asi a cciiain
oini, you won`i lcain lasici ly iiying io shovc
moic in, anu you mighi cvcn huii ihc ioccss.
10
Type and run the code.
Tyc anu iun ihc couc cxamlcs. Thcn you
can cxciimcni wiih changing anu imioving
ihc couc oi licaIing ii, which is somciimcs
ihc lcsi way io hguic oui whai`s ically
hacning). Ioi long cxamlcs oi Rcauy-laIc
couc, you can uownloau ihc souicc hlcs liom
hcauhisi|ava.com
:-l l: --l .- :l: l
-- ]--- -----.l--
9
Feel somethingl
Youi liain nccus io Inow ihai ihis ne.. Gci
involvcu wiih ihc sioiics. MaIc u youi own
caiions loi ihc hoios. Gioaning ovci a lau
|oIc is .II lciici ihan lccling noihing ai all.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
xxviii intro
You uo ro nccu any oihci ucvclomcni iool, such as an Inicgiaicu
Dcvclomcni Enviionmcni IDE). Wc siiongly iccommcnu ihai you ro
usc anyihing lui a lasic icxi cuiioi uniil you comlcic ihis looI anu
ee.nII, noi uniil alici chaici 16). An IDE can ioicci you liom somc ol
ihc uciails ihai ically maiici, so you`ic much lciici oll lcaining liom ihc
commanu-linc anu ihcn, oncc you ically unucisianu whai`s hacning,
movc io a iool ihai auiomaics somc ol ihc ioccss.
Whz! yee ncc4 fer !h|s |eek:
5lk6 P lkk
ll you dor'l a|ready |ave a 1.5 or realer Java 2 8tandard Ed|t|on 80K (3ollWare
0eve|oprerl K|l), you reed |l. ll you're or L|rux, w|rdoWs, or 3o|ar|s, you car el |l lor lree
lror java.sur.cor (3ur's Weos|le lor Java deve|opers). ll usua||y la|es ro rore l|ar lWo c||c|s
lror l|e ra|r pae lo el lo l|e J23E doWr|oads pae. 0el l|e |alesl non-oera vers|or posled.
T|e 30K |rc|udes everyl||r you reed lo corp||e ard rur Java.
ll you're rurr|r Vac 03 X 10.1, l|e Java 30K |s a|ready |rsla||ed. ll's parl ol 03 X, ard you
dor'l |ave lo do anyrn|ng e|se. ll you're or ar ear||er vers|or ol 03 X, you |ave ar ear||er
vers|or ol Java l|al W||| Wor| lor 95 ol l|e code |r l||s ooo|.
Nole: T||s ooo| |s oased or Java 1.5, oul lor slurr|r|y urc|ear rar|el|r reasors, s|orl|y
oelore re|ease, 3ur rerared |l Java 5, W|||e sl||| |eep|r '1.5 as l|e vers|or ruroer lor l|e
deve|oper's ||l. 3o, |l you see Java 1.5 or Java 5 or Java 5.0, or T|er (vers|or 5's or||ra|
code-rare), rney a|| mean rne same rn|ng. T|ere Was rever a Java 3.0 or 1.0|l jurped lror
vers|or 1.1 lo 5.0, oul you W||| sl||| l|rd p|aces W|ere |l's ca||ed 1.5 |rslead ol 5. 0or'l as|.
(0|, ard jusl lo ra|e |l rore erlerla|r|r, Java 5 ard l|e Vac 03 X 10.1 Were ool| |ver l|e
sare code-rare ol 'T|er, ard s|rce 03 X 10.1 |s l|e vers|or ol l|e Vac 03 you reed lo rur
Java 5, you'|| |ear peop|e la|| aooul 'T|er or T|er. ll jusl rears Java 5 or 03 X 10.1).
T|e 30K does nor |rc|ude l|e AP| documentat|on, ard you reed l|all 0o oac| lo java.sur.
cor ard el l|e J23E APl docurerlal|or. You car a|so access l|e APl docs or||re, W|l|oul
doWr|oad|r l|er, oul l|al's a pa|r. Trusl us, |l's Worl| l|e doWr|oad.
You reed a text ed|tor. v|rlua||y ary lexl ed|lor W||| do (v|, eracs, p|co), |rc|ud|r l|e 0ul ores
l|al core W|l| rosl operal|r syslers. Nolepad, wordpad, TexlEd|l, elc. a|| Wor|, as |or as
you ra|e sure l|ey dor'l apperd a '.lxl or lo l|e erd ol your source code.
0rce you've doWr|oaded ard urpac|ed/z|pped/W|alever (deperds or W||c| vers|or ard lor
W||c| 03), you reed lo add ar erlry lo your PATh erv|rorrerl var|ao|e l|al po|rls lo l|e /o|r
d|reclory |rs|de l|e ra|r Java d|reclory. For exarp|e, |l l|e J230K puls a d|reclory or your
dr|ve ca||ed 'j2sd|1.5.0, |oo| |rs|de l|al d|reclory ard you'|| l|rd l|e 'o|r d|reclory W|ere l|e
Java o|rar|es (l|e loo|s) ||ve. T|a o|r d|reclory |s l|e ore you reed a PATl lo, so l|al W|er you
lype:
al l|e corrard-||re, your lerr|ra| W||| |roW |oW lo l|rd l|e javao corp||er.
Nole: |l you |ave lrouo|e W|l| you |rsla||al|or, We recorrerd you o lo javararc|.cor, ard jo|r
l|e Java-8e|rr|r lorurl Aclua||y, you s|ou|d do l|al W|el|er you |ave lrouo|e or rol.
Note: much of the code from this book is available at wickedlysmart.com
how to use this book
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
the intro
you are here xxix
This is a lcaining cxciicncc, noi a iclcicncc looI. Wc uclilciaicly
siiicu oui cvciyihing ihai mighi gci in ihc way ol Ien.r.r whaicvci ii
is wc`ic woiIing on ai ihai oini in ihc looI. Anu ihc hisi iimc ihiough,
you nccu io lcgin ai ihc lcginning, lccausc ihc looI maIcs assumiions
aloui whai you`vc alicauy sccn anu lcaincu.
We use simple UML-like diagrams.
Il wc`u uscu u.e UMI, you`u lc sccing somcihing ihai IooI liIc ]ava, lui
wiih syniax ihai`s |usi lain w.or. So wc usc a simlihcu vcision ol UMI
ihai uocsn`i conuici wiih ]ava syniax. Il you uon`i alicauy Inow UMI, you
won`i havc io woiiy aloui lcaining ]ava nrJ UMI ai ihc samc iimc.
We don't worry about organizing and packaging your own
code until the end of the book.
In ihis looI, you can gci on wiih ihc lusincss ol lcaining ]ava, wiihoui
siicssing ovci somc ol ihc oiganizaiional oi auminisiiaiivc uciails ol
ucvcloing ]ava iogiams. You w.II, in ihc ical woilu, nccu io Inow-anu
usc-ihcsc uciails, so wc covci ihcm in ucih. Bui wc savc ihcm loi ihc cnu
ol ihc looI chaici 17). Rclax whilc you casc inio ]ava, gcnily.
The end-of-chapter exercises are mandatory; puzzles are
optional. Answers for both are at the end of each chapter.
Onc ihing you nccu io Inow aloui ihc uzzlcs-Le,`.e u..Ie. As in logic
uzzlcs, liain icascis, ciosswoiu uzzlcs, cic. Thc e:e..e aic hcic io hcl
you iaciicc whai you`vc lcaincu, anu you shoulu uo ihcm all. Thc uzzlcs
aic a uillcicni sioiy, anu somc ol ihcm aic quiic challcnging in a u..Ie
way. Thcsc uzzlcs aic mcani loi u..Ie., anu you iolally alicauy Inow il
you aic onc. Il you`ic noi suic, wc suggcsi you givc somc ol ihcm a iiy, lui
whaicvci hacns, uon`i lc uiscouiagcu il you nr` solvc a uzzlc oi il you
simly can`i lc loihcicu io iaIc ihc iimc io woiI ihcm oui.
The 8harpen Your Pencil' exercises don't have answers.
Noi iinicu in ihc looI, anyway. Ioi somc ol ihcm, ihcic . no iighi
answci, anu loi ihc oihcis, aii ol ihc lcaining cxciicncc loi ihc Shaicn
aciiviiics is loi ,ou io ucciuc il anu whcn youi answcis aic iighi. Somc ol
oui ueeJ answcis aic availallc on wicIculysmaii.com)
The code examples are as lean as possible
Ii`s liusiiaiing io wauc ihiough 200 lincs ol couc looIing loi ihc iwo lincs
you nccu io unucisianu. Mosi cxamlcs in ihis looI aic shown wiihin ihc
smallcsi ossillc conicxi, so ihai ihc aii you`ic iiying io lcain is clcai anu
simlc. So uon`i cxcci ihc couc io lc iolusi, oi cvcn comlcic. Thai`s
,ou. assignmcni loi alici you hnish ihc looI. Thc looI cxamlcs aic
wiiiicn sccihcally loi Ien.r.r, anu aicn`i always lully-lunciional.
Izs!-m|ne!c !h|n]s yee ncc4 !e knew:
s|ze
oar|()
eal()
c|aseCal()
w
- -:- . :-|--,
--- .-~cM
|
/-- :--| - A||
- l- .--- ]---
--:|' .:ll-:
+,-+ :+ ,-+:.|
A:ll-: -.-- -l l-
!--::- |----- :--` |--
.-- -.-.l--]' l--'l :
l-- ]--'-- :----: .--l
|-.--- )..
| ]-- :-- l- |---|- |--, l-
.:ll] : -l--.|, .- ]--
--'l |- l-:l] |-: -- :--::~
--- ---|-:, ]-- ---'l |- l-:-
-l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
xxx intro
Icrhn|rz| I4| !ers
]css woiIs ai Hcwlcii-PacIaiu on ihc Scll-
Hcaling Sciviccs Tcam. Shc has a Bachcloi`s
in Comuici Engincciing liom Villanova
Univcisiiy, has hci SCP] 1.4 anu SCWCD
cciiihcaiions, anu is liicially monihs away
liom iccciving hci Masicis in Soliwaic
Engincciing ai Dicxcl Univcisiiy whcw!)
Whcn shc`s noi woiIing, siuuying oi
moioiing in hci MINI Cooci S, ]css can
lc lounu hghiing hci cai loi yain as shc
comlcics hci laicsi Iniiiing oi ciochci
io|cci anylouy wani a hai.) Shc is
oiiginally liom Sali IaIc Ciiy, Uiah no,
shc`s noi Moimon... ycs, you wcic ioo
going io asI) anu is cuiicnily living ncai
Philauclhia wiih hci huslanu, Mcnuia, anu
iwo cais: Chai anu SaIc.
You can caich hci mouciaiing icchnical
loiums ai |avaianch.com.
Valcntin Valcniin Ciciiaz has a Masicis ucgicc
in Inloimaiion anu Comuici Scicncc liom
ihc Swiss Icucial Insiiiuic ol Tcchnology in
Iausannc EPII). Hc has woiIcu as a soliwaic
cngincci wiih SRI Inicinaiional Mcnlo PaiI,
CA) anu as a iincial cngincci in ihc Soliwaic
Engincciing Ialoiaioiy ol EPII.
Valcniin is ihc co-lounuci anu CTO ol Conuiis
Tcchnologics, a comany sccializing in ihc
ucvclomcni ol soliwaic aichiicciuic soluiions.
His icscaich anu ucvclomcni inicicsis
incluuc ascci-oiicnicu icchnologics, ucsign
anu aichiicciuial aiicins, wcl sciviccs, anu
soliwaic aichiicciuic. Bcsiucs iaIing caic ol
his wilc, gaiucning, icauing, anu uoing somc
soii, Valcniin mouciaics ihc SCBCD anu
SCD]WS loiums ai ]avaianch.com. Hc holus
ihc SC]P, SC]D, SCBCD, SCWCD, anu SCD]WS
cciiihcaiions. Hc has also hau ihc ooiiuniiy
io scivc as a co-auihoi loi Whizlals SCBCD
Exam Simulaioi.
Wc`ic siill in shocI liom sccing him in a .)
)-:::. .-l
)-:::.': M
|N|
Cicuii gocs io all, lui misiaIcs aic ihc solc iconsililiiy ol ihc
auihoi...". Docs anyonc ically lclicvc ihai. Scc ihc iwo colc on
ihis agc. Il you hnu icchnical iollcms, ii`s iolally lauli. : )
/.|--l- c--ll.-
/.|--l-': l-
tech editing: Jessica and VaIentin
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
the intro
you are here xxxi
0!hcr pcep|c !e ||zmc:
At O`ReiIIy:
Oui liggcsi ihanIs io Mikc Loukidcs ai O`Rcilly, loi iaIing a
chancc on ihis, anu hcling io shac ihc Hcau Iiisi concci inio
a looI anu e..e). As ihis scconu cuiiion gocs io iini ihcic
aic now hvc Hcau Iiisi looIs, anu hc`s lccn wiih us all ihc way.
To Tim O'Rcilly, loi his willingncss io launch inio somcihing
oIeeI, ncw anu uillcicni. ThanIs io ihc clcvci Kylc Hart loi
hguiing oui how Hcau Iiisi his inio ihc woilu, anu loi launching
ihc sciics. Iinally, io Edic Frccdman loi ucsigning ihc Hcau Iiisi
cmhasizc ihc LenJ" covci.
Our intrepid beto testers ond reviewer teom:
Oui io honois anu ihanIs go io ihc uiiccioi ol oui |avaianch
icch icvicw icam, ]ohanncs dc ]ong. This is youi hlih iimc aiounu
wiih us on a Hcau Iiisi looI, anu wc`ic ihiillcu you`ic siill scaIing
io us. ]cII Cumps is on his ihiiu looI wiih us now anu iclcnilcss
aloui hnuing aicas whcic wc nccucu io lc moic clcai oi coiicci.
Corcy McGlonc, you iocI. Anu wc ihinI you givc ihc clcaicsi
cxlanaiions on |avaianch. You`ll iolally noiicc wc siolc onc oi
iwo ol ihcm. ]ason Mcnard savcu oui icchnical luiis on moic
ihan a lcw uciails, anu Thomas Paul, as always, gavc us cxcii
lcculacI anu lounu ihc sulilc ]ava issucs ihc icsi ol us misscu.
]anc Griscti has hci ]ava chos anu Inows a ihing oi iwo aloui
w...r) anu ii was gicai io havc hci hcling on ihc ncw cuiiion
along wiih long-iimc |avaianchci Barry Gaunt.
Marilyn dc Quciroz gavc us cxccllcni hcl on boL cuiiions ol ihc
looI. Chris ]oncs, ]ohn Nyquist, ]amcs Cubcta, Tcrri Cubcta,
anu Ira Bcckcr gavc us a ion ol hcl on ihc hisi cuiiion.
Sccial ihanIs io a lcw ol ihc Hcau Iiisicis who`vc lccn hcling
us liom ihc lcginning: Angclo Cclcstc, Mikalai Zaikin, anu
Thomas DuII iwuull.com). Anu ihanIs io oui iciiihc agcni, Daviu
Rogcllcig ol SiuuioB lui sciiously, whai aloui ihc o..e iighis.)
:--l
--- - --- )..
---l ------:
M.-|]- -
6-----
)-- N]-:l
|-. B-:--
---] )
w----
1--- c--l.
).--: c--l.
)-.---: - )--
)- c--:
c---] M:6|---
c-: )---:
1--.: |.-|
).:-- M
--.-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
xxxii intro
1es! whcn yee !hee]h! !hcrc wee|4n! |c zny
merc zrknew|c4]cmcn!s'.
More ]ovo technicoI experts who heIped out on the frst edition )in pseudo-rondom order;:
EmiIo Hoii, Michacl Tauiiz, MiIc Gallihugh, Manish Haiwalnc, ]amcs Chcgwiuucn,
Shwcia Maihui, Mohamcu Mazahim, ]ohn Pavciu, ]osch Bih, SIuliai Paianavanich,
Sunil Palicha, Suuuhasaiwa Ghosh, RamIi Siinivasan, Allicu Raoul, Angclo Cclcsic,
MiIalai ZaiIin, ]ohn Zociclici, ]im Plcgci, Baiiy Gauni, anu MaiI Diclcn.
The frst edition puzzIe teom:
DiiI SchiccImann, Maiy ]avaCioss Chamion" Icncis, Rouncy ]. Woouiull, Gavin Bong,
anu ]ason Mcnaiu. ]avaianch is lucIy io havc you all hcling oui.
Other co-conspirotors to thonh:
Paul Whcaton, ihc |avaianch Tiail Boss loi suoiiing ihousanus ol ]ava lcaincis.
Solvcig Haugland, misiicss ol ]2EE anu auihoi ol Daiing Dcsign Paiicins".
Auihois Dori Smith anu Tom Ncgrino (backupbrain.com), loi hcling us navigaic ihc
icch looI woilu.
Oui Hcau Iiisi aiincis in ciimc, Eric Frccman and Bcth Frccman auihois ol Hcau Iiisi
Dcsign Paiicins), loi giving us ihc Bawls io hnish ihis on iimc.
Shcrry Dorris, loi ihc ihings ihai ically maiici.
Brove EorIy Adopters o[ the Heod First series:
]oc Iiiion, Ross P. Golulcig, Dominic Da Silva, honcsiucI, Danny Biomlcig, Sichcn
Ic, Elion Hughcs, Eiic Chiisicnscn, Vulinh Nguycn, MaiI Rau, Aluulhal, Naihan
Olihani, Michacl Biauly, Alcx Daiiow, Michacl Iischci, Saiah Noiiingham, Tim Allcn,
Bol Thomas, anu MiIc Billy ihc hisi).
stiII more acknowIedgements
*The large number of acknowledgements is because we're testing the theory that everyone mentioned in
a book acknowledgement will buy at least one copy, probably more, what with relatives and everything. f
you'd like to be in the acknowledgement of our book, and you have a large family, write to us.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
this is a new chapter 1
Java takes you to new pIaces. Prom its humble release to the public as the
(wimpy) version l.02, 1ava seduced programmers with its friendly syntax, ob|ect-oriented features,
memory management, and best of all the promise of portability. The lure of write-once/run-
anywhere is |ust too strong. A devoted following exploded, as programmers fought against bugs,
limitations, and, oh yeah, the fact that it was dog slow. 8ut that was ages ago. |f you're |ust starting in
1ava, you're Iucky. Some of us had to walk ve miles in the snow, uphill both ways (barefoot), to
get even the most trivial applet to work. 8ut , why, get to ride the sIeeker, faster, much
more powerfuI 1ava of today.
B
re
a
kin
g
th
e
8
ur
f
a
ce
Come on, fhe wofer's
greofl We'II dive righf in ond
wrife some code, fhen compiIe ond
run if. We're foIking synfox, Iooping
ond bronching, ond o Iook of whof
mokes Jovo so cooI. You'II be
coding in no fime.
1 dive in A Quick Dip
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
2 chapter 1
Ieu 8eI
5heeI Me
Ihc Wzy 1zvz Werks
source code lor
l|e |rleracl|ve
parly |rv|lal|or.
Vel|od Parly()
0 a|oad_0
1 |rvo|espe-
c|a| #1 <Vel|od
java.|ar.0ojecl()>
1 relurr
Create a source
document. Use an
established protocol
(in this case, the 1ava
language).
8eerrc
0emp||cr
0e!pe!
|re4cI
V|r!ez|
Mzrh|ncs
The goal is to write one application {in this
example, an interactive party invitation} and have
it work on whatever device your friends have.
Pun your document
through a source code
compiler. The compiler
checks for errors and
won't let you compile
until it's satised that
everything will run
correctly.
0emp||cr
0e!pe!
|re4cI
V|r!ez|
Mzrh|ncs
1zvz 5.0
|vc rs|ens 1.5 zn4 epI
3500 classes
Mere ewer, ensier re
Jevele wirh.
8esides adding more than a
thousand additional classes,
1ava 5.0 (known as "Tiger)
added ma|or changes to
the language itself, making
it easier (at least in theory)
for programmers and giving
it new features that were
popular in other languages.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
dive In A Quick Dip
5
int size = 27,
String name = "Fido",
Dog myDog = new Dog{name, size|,
x = size ~ 5,
if {x < l5| myDog.bark{8|,
while {x > 3| {
myDog.play{|,
}
int numList = {2,4,6,8},
System.out.print{"Hello"|,
System.out.print{"Dog: " + name|,
String num = "8",
int z = Integer.parseInt{num|,
try {
readTheFile{"myFile.txt"|,
}
catch{FileNotFoundException ex| {
System.out.print{"File not found."|,
}
+,-+ :+ ,-+:.|
-:|.-- .- -l--- .-.|- -.-- ':--' .- - l l- .|-- i7
Try to guess what each line of code is doing...
(answers are on the next page).
Ieek hew czsy | !
|s !e wr| !c 1zvz.
I see 1ava 2 and 1ava 5.0, but was there a 1ava 3
and 4! And why is it 1ava 5.0 but not 1ava 2.0!
The |oys of marketing... when the version of 1ava
shifted from l.l to l.2, the changes to 1ava were so
dramatic that the marketers decided we needed a whole
new "name, so they started calling it Jnvn 2, even though
the actual version of 1ava was l.2. 8ut versions l.3 and l.4
were still considered Jnvn 2. There never a 1ava 3 or
4. 8eginning with 1ava version l.5, the marketers decided
once again that the changes were so dramatic that a
new name was needed (and most developers agreed), so
they looked at the options. The next number in the name
sequence would be "3, but calling 1ava l.5 Jnvn 3 seemed
more confusing, so they decided to name it Jnvn 5.0 to
match the "5 in version "l.5.
So, the original 1ava was versions l.02 (the first official
release) through l.l were |ust "1ava. versions l.2, l.3, and
l.4 were "1ava 2. And beginning with version l.5, 1ava is
called "1ava 5.0. 8ut you'll also see it called "1ava 5 (without
the ".0) and "Tiger (its original code-name). we have no
idea what will happen with the release...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
why Java is cooI
6 chapter 1
int size = 27,
String name = "Fido",
Dog myDog = new Dog{name, size|,
x = size ~ 5,
if {x < l5| myDog.bark{8|,
while {x > 3| {
myDog.play{|,
}
int numList = {2,4,6,8},
System.out.print{"Hello"|,
System.out.print{"Dog: " + name|,
String num = "8",
int z = Integer.parseInt{num|,
try {
readTheFile{"myFile.txt"|,
}
catch{FileNotFoundException ex| {
System.out.print{"File not found."|,
}
+,-+ :+ ,-+:.|
-:|.-- .- -l--- .-.|- -.-- ':--' .- - l l- .|-- i7
enr werry nbeur wherher yeu unJersrnnJ nny eI rhis yerl
Lverything here is explained in great detail in the book, most
within the rst 40 pages). |f 1ava resembles a language you've
used in the past, some of this will be simple. |f not, don't worry
about it. well et thete...
Ieek hew czsy | !
|s !e wr| !c 1zvz.
-:|.-- . :l-- - :.-.:l--: .-.|- -.-- '-.--' .- - l l- .|-- |-'
-:|.-- . --- l- .-.|- '-]l-' .- -.- l- --- l- -:- '-.--' .- ':--'
:-l-.:l - --- i7 |.|-- - ':--'` .- .::- l l- . .-.|- -.-- ''
|.|-- - ii` : |-:: l.- |-, l-|| l- - l- .- l--:
-- |--- .: |-- .: : --.l-- l.- ?
l-|| l- - l- |.] |-.l--- 1+A1 --.-: l- . -`
l: |--: |- l- -- - l- |-- ~~ ---]l- - ! : --- - l- |--
-:|.-- . |:l - -l---: .-.|- '---|:l', .- -l i,+,|, -l- l- |:l
--l --l +-||-' --.|] .l l- :---.-~|--
--l --l +-||- |-' |l- .|-- - '-.--' : |-'` .l l- :---.-~|--
-:|.-- . :.-.:l-- :l-- .-.|- '---' .- - l l- .|-- - '
:----l l- :l-- - :.-.:l--: ' -l- .- .:l-.| -----: .|--
l-] l- - :---l--.]- l- l- --'-- l-]- :-'l -.-.-l-- l- ---
--. . l-l |- -.-- -]||-ll' |-- .l |-.:l 1/ l- --. l- |-`
--:l - l- -- - l- l-: l- l-]', :- | --:: ]-- :--| l-] -.-] l-:
l: --:l - ---- ]-- - --l l- l- ]-- l-- -'l ---
l- l- -- l-- .|-, --l ||- --l ---' --l .l l- :---.-~|--
|--: |- ---]l- - l- ! : -.l l- - l- 'l-]' -'l ---
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
dive In A Quick Dip
7
What goes in a
source file?
public class Dog {
}
What goes in a
class?
public class Dog {
void bark() {
}
}
What goes in a
method?
public class Dog {
void bark() {
statement1;
statement2;
}
}
A souicc couc hlc wiih ihc .n.n
cxicnsion) holus onc cIoss uchni-
iion. Thc class icicscnis a .ee
ol youi iogiam, alihough a vciy
iiny alicaiion mighi nccu |usi
a singlc class. Thc class musi go
wiihin a aii ol cuily liaccs.
A class has onc oi moic methods.
In ihc Dog class, ihc borh mcihou
will holu insiiuciions loi how ihc
Dog shoulu laiI. Youi mcihous
musi lc ucclaicu .r.Je a class
in oihci woius, wiihin ihc cuily
liaccs ol ihc class).
r|zss
mc!he4
Wiihin ihc cuily liaccs ol a
mcihou, wiiic youi insiiuciions
loi how ihai mcihou shoulu lc
ciloimcu. Mcihou oJe is lasi-
cally a sci ol siaicmcnis, anu loi
now you can ihinI ol a mcihou
Iinu ol liIc a lunciion oi iocc-
uuic.
0e4c s!rer!erc |n 1zvz
s!z!cmcn!s
Put a class in a source hle.
Put methods in a class.
Put statements in a method.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
8 chapter 1
---- -.:- -
l
- -
-l
-
public class MyFirstApp {
public static void main (String[] args) {
System.out.print(I Rule!);
nz!emy ef z r|zss
Whcn ihc ]VM siaiis iunning, ii looIs loi ihc class you givc ii ai ihc com-
manu linc. Thcn ii siaiis looIing loi a sccially-wiiiicn mcihou ihai looIs
cxacily liIc:
public static void main (String[] args) {
// your code goes here
}
Ncxi, ihc ]VM iuns cvciyihing lciwccn ihc cuily liaccs [ } ol youi main
mcihou. Evciy ]ava alicaiion has io havc ai lcasi onc , anu ai lcasi
onc mcihou noi onc main ci In, |usi onc main ci nI.n.or).
-|: :- ---]---
:.- .::-:: l
l: : .
:|.:: |-`
l- -.-- -
l: :|.::
---- :--|] -.:-
- l- :|.::
|--'|| :--- l:
--- |.l--`
l- --l--- l]-
- --.-: l---':
-- --l--- .|--
l- -.-- -
l: --l-
.-----l: l- l- --l-
1: --l- --:l - --
.- .--.] - l--:, .- l-
.--.] -|| - :.||- '.-:'
l: :.]: --l l- :l.-.- --l-l
|-.-|l: l- :---.-~|--`
l- l-- ]--
-.-l l- --l
---] :l.l----l Mc1
-- - . :--:-|--''
:|-:- -.:- - l- -.- --l-
:|-:- -.:- - l- M]|-:lA :|.::
}
}
a Java cIass
l--'l ----] .--l ------- .-]l- -l ---
l: :.l-- : -:l l- -l ]-- :l.-l-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
dive In A Quick Dip
9
MyFirstApp.class
Wr| !|n] z r|zss w| !h z
In ]ava, cvciyihing gocs in a class. You`ll iyc youi souicc couc hlc wiih a
.n.n cxicnsion), ihcn comilc ii inio a ncw class hlc wiih a .In cxicnsion).
Whcn you iun youi iogiam, you`ic ically iunning a In.
Running a iogiam mcans iclling ihc ]ava Viiiual Machinc ]VM) io Ioau ihc
Hello class, ihcn siaii cxccuiing iis main() mcihou. Kcc iunning iil all ihc
couc in main is hnishcu."
In chaici 2, wc go uccci inio ihc wholc In ihing, lui loi now, all you nccu io
ihinI is, how do I write ]ovo code so thot it wiII run Anu ii all lcgins wiih main().
Thc main() mcihou is whcic youi iogiam siaiis iunning.
No maiici how lig youi iogiam is in oihci woius, no maiici how many Ine
youi iogiam uscs), ihcic`s goi io lc a main() mcihou io gci ihc lall iolling.
public class MyFirstApp {
public static void main (String[] args) {
System.out.println(I Rule!);
System.out.println(The World);
}
}
Save
MyFirstApp.java
CompiIe
javac MyFirstApp.java
Run
puo||c c|ass VyF|rslApp {
puo||c slal|c vo|d ra|r
(3lr|r[| ars) {
3ysler.oul.pr|rl('l Ru|el),
MyFirstApp.]ava
Vel|od Parly() 0 a|oad_0 1
|rvo|espec|a| #1 <Vel|od
java.|ar.0ojecl()>
1 relurr
Vel|od vo|d
ra|r(java.|ar.3lr|r[|)
0 elslal|c #2 <F|e|d
File Edit Window Help Scream
%java MyFirstApp
I Rule!
The World
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
10 chapter 1
Oncc you`ic insiuc main oi mcihou), ihc lun
lcgins. You can say all ihc noimal ihings ihai you say
in mosi iogiamming languagcs io mohe the computer
do something.
Youi couc can icll ihc ]VM io:
4e semc!h|n]
Statements: declarations, assignments,
method calls, etc.
int x = 3;
String name = Dirk;
x = x * 17;
System.out.print(x is + x);
double d = Math.random();
// this is a comment
.-
': :-||.-
.: )
..
-ll-- ---
)
..
l-.:l--
Men4zy mern|n] z! Be|s
Could this story be trueI es and no. while there ote versions of 1ava running in de-
vices including PDAs, cell phones (esec|olly cell phones), pagers, rings, smart cards,
and more -you might not find a 1ava toaster or dog collar. 8ut even if you can't
find a 1ava-enabled version of your favorite gadget, you can still run it as if it wete a
1ava device by controlling it through some other interface (say, your laptop) that |s
running 1ava. This is known as the 1ini suttoote otch|tectute. es you con have that
geek dream home.
CaJe Kagaets
A working 1ava program is all scrambled up
on the fridge. Can you rearrange the code
snippets to make a working 1ava program
that produces the output listed belowI
Some of the curly braces fell on the floor
and they were too small to pick up, so feel
free to add as many of those as you need!
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
22 chapter 1
l 2 3
4 5 6
7
8 9 l0 ll
l2
l3
l4 l5 l6
l7
l8 l9
20
2l
Let's give your right brain something to do.
|t's your standard crossword, but almost all
of the solution words are from chapter l. 1ust
to keep you awake, we also threw in a few
(non-1ava) words from the high-tech world.
4. Command-line invoker
6. 8ack againI
8. Can't go both ways
9. Acronym for your laptop's power
l2. number variable type
l3. Acronym for a chip
l4. Say something
l8. Quite a crew of characters
l9. Announce a new class or method
2l. what's a prompt good forI
-.l: -.:
:.-.l- -l
--- - l-
-::|- --l-l:
class Test {
public static void main(String [] args) {
int x = 0;
int y = 0;
while ( x < 5 ) {
System.out.print(x + + y + );
x = x + 1;
}
}
}
y = x ~ y,
y = y + x,
y = y + 2,
if{ y > 4 | {
y = y ~ l,
}
x = x + l,
y = y + x,
if { y < 5 | {
x = x + l,
if { y < 3 | {
x = x ~ l,
}
}
y = y + 2,
22 46
ll 34 59
02 l4 26 38
02 l4 36 48
00 ll 2l 32 42
ll 2l 32 42 53
00 ll 23 36 4l0
02 l4 25 36 47
Candidates: PossibIe output:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
24 chapter 1
System.out.print(" ),
System.out.print("a "),
System.out.print("n "),
System,out,print("an"),
x x + l,
x x + 2,
x x - 2,
x x - l,
x > 0
x < l
x > l
x > 3
x < 4
System.out.print("noys "),
System.out.print("oise "),
System.out.print(" oyster "),
System.out.print("annoys),
System.out.print("noise),
our is to take code snippets from the
pool and place them into the blank
lines in the code. ou may not use the
same snippet more than once, and
you won't need to use all the snip-
pets. our is to make a class that
will compile and run and produce the
output listed. Don't be fooledthis one's
harder than it looks.
class PoolPuzzleOne {
public static void main{String args| {
int x = 0,
while { __________ | {
_____________________________
if { x < l | {
___________________________
}
_____________________________
if { __________ | {
____________________________
___________
}
if { x == l | {
____________________________
}
if { ___________ | {
____________________________
}
System.out.println{""|,
____________
}
}
}
Note: ach snippet
from the pooI can be
used onIy oncel
File Edit Window Help Cheat
%java PoolPuzzleOne
a noise
annoys
an oyster
Dutput
puzzIe: PooI PuzzIe
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
dive In A Quick Dip
25
File Edit Window Help Poet
% java Shuffle1
a-b c-d
class Shufel {
public static void main{String args| {
int x = 3,
while {x > 0| {
if {x > 2| {
System.out.print{"a"|,
}
x = x ~ l,
System.out.print{"~"|,
if {x == 2| {
System.out.print{"b c"|,
}
if {x == l| {
System.out.print{"d"|,
x = x ~ l,
}
}
}
}
class Exerciselb {
public static void main{String args| {
int x = l,
while { x < l0 | {
x ~ x + I,
if { x > 3| {
System.out.println{"big x"|,
}
}
} This wiII compiIe ond run (no oufpuf), buf
} wifhouf o Iine odded fo fhe progrom, if
wouId run forever in on infnife 'whiIe' Ioopl
cIoss Foo {
public static void main{String args| {
int x = 5,
while { x > l | {
x = x ~ l,
if { x < 3| {
System.out.println{"small x"|,
}
} This fIe won'f compiIe wifhouf o
} cIuss decIurution und don't forget
} fhe mofching curIy broce l
class Exerciselb {
pubIic sfofic void moin(Sfring [] orgs) {
int x = 5,
while { x > l | {
x = x ~ l,
if { x < 3| {
System.out.println{"small x"|,
}
}
}
}
A
C
Code Mognefs:
]e;ejze o|ajoz
The 'whiIe' Ioop code musf be in-
side o mefhod. If con'f jusf be
honging ouf inside fhe cIoss.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
26 chapter 1
l 2 3
4 5 6
7
8 9 l0 ll
l2
l3
l4 l5 l6
l7
l8 l9
20
2l
J A V A
P
P
A
Y
S
8 A M C H
S
T
A
T
I
C
M
A
I
M
Y T E O U T P P I M T
W
I
L
M T
S P I 0 D E C L A P E
C O M M A M D
J
V
M
T
H
O
I C
P
U
8
L
I
V
A
P
A
8
E
C
O
M
I
L
P
V
O
I
D
F
L
O
A
O P
class PoolPuzzleOne {
public static void main{String args| {
int x = 0,
while { X - 4 | {
System,out,print{"u"};
if { x < l | {
System,out,print{" "};
}
System,out,print{"n"};
if { X > 1 | {
System,out,print{" oyster"};
= + Z;
}
if { x == l | {
System,out,print{"noys"};
}
if { X - 1 | {
System,out,print{"oise"};
}
System.out.println{""|,
X = X + 1;
}
}
}
File Edit Window Help Cheat
%java PoolPuzzleOne
a noise
annoys
an oyster
class Test {
public static void main(String [] args) {
int x = 0;
int y = 0;
while ( x < 5 ) {
System.out.print(x + + y + );
x = x + 1;
}
}
}
y = x ~ y,
y = y + x,
y = y + 2,
if{ y > 4 | {
y = y ~ l,
}
x = x + l,
y = y + x,
if { y < 5 | {
x = x + l,
if { y < 3 | {
x = x ~ l,
}
}
y = y + 2,
22 46
ll 34 59
02 l4 26 38
02 l4 36 48
00 ll 2l 32 42
ll 2l 32 42 53
00 ll 23 36 4l0
02 l4 25 36 47
Candidates: PossibIe output:
puzzIe answers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
2 cIasses and objects
this is a new chapter 27
I was toId there wouId be objects. |n chapter l, we put all of our code in the
main() method. That's not exactly ob|ect-oriented. |n fact, that's not ob|ect-oriented ot oll. well,
we did use a few ob|ects, like the String arrays for the Phrase-O-Matic, but we didn't actually
develop any of our own ob|ect tyes. So now we've got to leave that procedural world behind,
get the heck out of main(), and start making some ob|ects of our own. we'll look at what makes
ob|ect-oriented (OO) development in 1ava so much fun. we'll look at the difference between
a closs and an ooject. we'll look at how ob|ects can give you a better life (at least the program-
ming part of your life. Not much we can do about your fashion sense). warning: once you get
to Ob|ectville, you might never go back. Send us a postcard.
A Trip to Ob]ectville
We're going fo
ObjecfviIIel We're
Ieoving fhis dusfy oI'
proceduroI fown for good.
I'II send you o posfcord.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
once upon a time in ObjectviIIe
28 chapter 2
!hc spcr
ncc uon a iimc in a soliwaic sho, iwo
iogiammcis wcic givcn ihc samc scc anu iolu io
luilu ii". Thc Rcally Annoying Pio|cci Managci
loiccu ihc iwo coucis io comcic,
ly iomising ihai whocvci uclivcis
hisi gcis onc ol ihosc cool Acion
chaiis all ihc Silicon Vallcy guys havc.
Iaiiy, ihc ioccuuial iogiammci, anu
Biau, ihc OO guy, loih Incw ihis woulu
lc a iccc ol caIc.
Iaiiy, siiiing in his culc, ihoughi io
himscll, Whai aic ihc ihings ihis iogiam
has io Jo. Whai procedures uo wc nccu.".
Anu hc answcicu himscll , rotatc anu
playSound." So oll hc wcni io luilu ihc
ioccuuics. Alici all, whai . a iogiam il noi
a ilc ol ioccuuics.
Biau, mcanwhilc, IicIcu lacI ai ihc calc
anu ihoughi io himscll, Whai aic ihc things
in ihis iogiam... who aic ihc Icy In,e.." Hc
hisi ihoughi ol Thc Shapcs. Ol couisc, ihcic
wcic oihci ol|ccis hc ihoughi ol liIc ihc Usci, ihc Sounu,
anu ihc ClicIing cvcni. Bui hc alicauy hau a liliaiy ol couc
loi ihosc icccs, so hc locuscu on luiluing Shacs. Rcau
on io scc how Biau anu Iaiiy luili ihcii iogiams, anu
loi ihc answci io youi luining qucsiion, So, who got the
Aeron`
0hz|r Wzrs
|er Hew 0|jcr!s 0zn 0hzn]c Yeer I|fcI
!hc rhz|r
! Brz4s |zp!ep z! !hc rzfc
Biau wioic a cIoss loi cach ol ihc ihicc shacs
|n Izrrys re|c
As hc hau uonc a gazillion iimcs lcloic, Iaiiy
sci aloui wiiiing his Important Proccdurcs.
Hc wioic rotatc anu playSound in no iimc.
rotate(shapeNum) {
// make the shape rotate 360
}
playSound(shapeNum) {
// use shapeNum to lookup which
// AIF sound to play, and play it
}
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
cIasses and objects
29
1here
w
ill re
an
an
cera
shae
cn
|he
screen, w
i|h
|he
c|hers.
T
hen
|he
user
clicks
cn
|he
an
cera, i| w
ill rc|a|e
like
|he
c|hers, ana
lay
a
.hil scuna
lile
Be! wz| !| Ihcrcs |ccn z spcr rhzn]c.
OK, eLr.nII, you wcic hisi, Iaiiy," saiu ihc Managci, lui wc havc io auu |usi onc
iiny ihing io ihc iogiam. Ii`ll lc no iollcm loi ciacI iogiammcis liIc you iwo."
I I LnJ n J.e o. e.e., .e I`.e Len.J Ln ore`, ihoughi Iaiiy, Inowing ihai scc-
changc-no-iollcm was a laniasy. ArJ ,e B.nJ IooI .nreI, e.ere. VLn` u w.L
Ln:` Siill, Iaiiy hclu iighi io his coic lclicl ihai ihc OO way, whilc cuic, was |usi
slow. Anu ihai il you wanicu io changc his minu, you`u havc io iy ii liom his colu,
ucau, caial-iunncllcu hanus.
Izrry !hee]h! hc4 nz||c4 | !. Hc ree|4 z|mes! fcc| !hc re||c4
s!cc| ef !hc cren |cncz!h h|s...
whz! ]e! z44c4 !e !hc spcr
Bzrk |n Izrrys re|c
Thc ioiaic ioccuuic woulu siill woiI, ihc couc uscu
a looIu iallc io maich a shacNum io an aciual
shac giahic. Bui pIoySound wouId hove to chonge.
Anu whai ihc hccI is a .hil hlc.
playSound(shapeNum) {
// if the shape is not an amoeba,
// use shapeNum to lookup which
// AIF sound to play, and play it
// else
// play amoeba .hif sound
}
Ii iuincu oui noi io lc such a lig ucal, lui it stiII
mode him queosy to touch previousIy-tested code. Ol
nII colc, Le shoulu Inow ihai no maiici whai ihc
io|cci managci says, the spec oIwoys chonges.
! Brz4s |zp!ep z! !hc |czrh
Biau smilcu, sicu his maigaiiia, anu w.oe ore
rew In. Somciimcs ihc ihing hc lovcu mosi
aloui OO was ihai hc uiun`i havc io iouch couc
hc`u alicauy icsicu anu uclivcicu. Ilcxililiiy,
cxicnsililiiy,..." hc muscu, icucciing on ihc
lcnchis ol OO.
rolale() {
// code lo rolale ar aroeoa
p|ay3ourd() {
// code lo p|ay l|e reW
// .||l l||e lor ar aroeoa
.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
once upon a time in ObjectviIIe
30 chapter 2
An
ecra
rc|a|icn
cin| in
Iarry
ana
Braa`s
versicn:
T
here
|he
an
era
rc|a|icn
cin| shcula
re:
Whz! !hc spcr renvcn|cn!| y
fer]e! !e mcn!|en
Hah! So much loi ihai looly OO nonscnsc). Bui ihc smiiI on Iaiiy`s lacc mclicu whcn ihc
Rcally Annoying Pio|cci Managci saiu wiih ihai ionc ol uisaoinimcni), Oh, no, Ln` noi
how ihc amocla is suoscu io ioiaic..."
Tuins oui, loih iogiammcis hau wiiiicn ihcii ioiaic couc liIc ihis:
1} determine the rectangle that surrounds the shape
2} calculate the center of that rectangle, and rotate the shape around that point.
Bui ihc amocla shac was suoscu io ioiaic aiounu a oini on onc erJ, liIc a clocI hanu.
I`m ioasi." ihoughi Iaiiy, visualizing chaiicu Wonucilicau. Alihough, hmmmm. I coulu
|usi auu anoihci il/clsc io ihc ioiaic ioccuuic, anu ihcn |usi haiu-couc ihc ioiaiion oini
couc loi ihc amocla. Thai iolally won`i licaI anyihing." Bui ihc liiilc voicc ai ihc lacI ol
his hcau saiu, B. A.nIe. Do ,ou LoreI, L.rI Le e wor` Lnre nn.r:`
Izrry snerk |n jes! memcn!s zhcz4 ef Brz4.
Bzrk |n Izrrys re|c
Hc hguicu hc lciici auu ioiaiion oini aigumcnis
io ihc ioiaic ioccuuic. A Iot o[ code wos o[[ected.
Tcsiing, iccomiling, ihc wholc ninc yaius all ovci
again. Things ihai uscu io woiI, uiun`i.
rotate(shapeNum, xPt, yPt) {
// if the shape is not an amoeba,
// calculate the center point
// based on a rectangle,
// then rotate
// else
// use the xPt and yPt as
// the rotation point offset
// and then rotate
}
! Brz4s |zp!ep en h|s |zwn
rhz|r z! !hc Ic||er|4c B|ec]rzss Ics!| vz|
Wiihoui missing a lcai, Biau mouihcu ihc ioiaic
mcthod, lui only in ihc Amocla class. He never
touched the tested, worhing,
compiIed code loi ihc oihci
aiis ol ihc iogiam. To
givc ihc Amocla a ioia-
iion oini, hc auucu an
attributc ihai all Amoclas
woulu havc. Hc moui-
hcu, icsicu, anu uclivcicu
wiiclcssly) ihc icviscu
iogiam uuiing a singlc
Bcla IlccI sci.
|rl xPo|rl
|rl yPo|rl
rolale() {
// code lo rolale ar aroeoa
// us|r aroeoa's x ard y
p|ay3ourd() {
// code lo p|ay l|e reW
// .||l l||e lor ar aroeoa
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
cIasses and objects
31
8e, Brz4 !hc 00 ]ey ]e! !hc rhz|r, r|]h! !
Not so [ost. Iaiiy lounu a uaw in Biau`s aioach. Anu,
sincc hc was suic ihai il hc goi ihc chaii hc`u also gci Iucy
in accouniing, hc hau io iuin ihis ihing aiounu.
LARRY: You`vc goi uulicaicu couc! Thc ioiaic
ioccuuic is in all loui Shac ihings.
BRAD: Ii`s a method, noi a .oeJu.e. Anu ihcy`ic cIosses,
noi L.r.
LARRY: Whaicvci. Ii`s a siuiu ucsign. You havc io
mainiain ou. uillcicni ioiaic mcihous". How can ihai
cvci lc goou.
BRAD: Oh, I gucss you uiun`i scc ihc hnal ucsign. Ici mc
show you how OO inhcritancc woiIs, Iaiiy.
Whz! Izrry wzn!c4
|f|]erc4 !hc rhz|r wee|4 |mprcss hcrI
Ihcyrc 8hzpcs, zn4 !hcy z| | re!z!c zn4
p|zy8een4. 8e | z|s!rzr!c4 ee! !hc
remmen fcz!ercs zn4 pe! !hcm |n!e z
ncw r|zss rz| |c4 8hzpc.
3|ape
rolale()
p|ay3ourd()
Tr|ar|e 3quare C|rc|e Aroeoa
3|ape
rolale()
p|ay3ourd()
sepcrr|zss
se|r|zsscs
Ihcn | ||nkc4 !hc e!hcr
feer shzpc r|zsscs !e
!hc ncw 8hzpc r|zss,
|n z rc|z!|ensh|p rz||c4
|nhcr| !znrc.
Tr|ar|e
rolale()
p|ay3ourd()
3quare
rolale()
p|ay3ourd()
C|rc|e
rolale()
p|ay3ourd()
| |eekc4 z! whz! z|| feer
r|zsscs hzvc |n remmen.
Aroeoa
rolale()
p|ay3ourd()
j[ z( j( ([j, wzy...
One analogy for ob|ects is a packet of unused Polodex cards.
Lach card has the same blank fields (the instance variables). when
you fill out a card you are creating an instance (ob|ect), and the
entries you make on that card represent its state.
The methods of the class are the things you do to a particular card,
getName( ), changeName( ), setName( ) could all be methods for
class Polodex.
So, each card can the same things (getName( ), changeName( ),
etc.), but each card things unique to that particular card.
An object is Iike one entry in your address book.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
36 chapter 2
class DogTestDrive {
public static void main (String[] args) {
Dog d = new Dog();
d.size = 40;
d.bark();
}
}
000
s|ze
oreed
rare
oar|()
making objects
class Dog {
int size;
String breed;
String name;
void bark() {
System.out.println(Ruff! Ruff!);
}
}
Mzk|n] yeer f|rs! e|jcr!
So whai uocs ii iaIc io cicaic anu usc an ol|cci. You nccu wo classcs. Onc
class loi ihc iyc ol ol|cci you wani io usc Dog, AlaimClocI, Tclcvision,
cic.) anu anoihci class io e youi ncw class. Thc ee. class is whcic you ui
ihc main mcihou, anu in ihai main) mcihou you cicaic anu acccss ol|ccis
ol youi ncw class iyc. Thc icsici class has only onc |ol: io ., ou ihc mcih-
ous anu vaiiallcs ol youi ncw ol|cci class iyc.
Iiom ihis oini loiwaiu in ihc looI, you`ll scc iwo classcs in many ol
oui cxamlcs. Onc will lc ihc .enI class - ihc class whosc ol|ccis wc
ically wani io usc, anu ihc oihci class will lc ihc ee. class, which wc
call <wLne.e.You.CInNneI> TestDrive. Ioi cxamlc, il wc maIc a
Bungee class, wc`ll nccu a BungeeTestDrive class as wcll. Only ihc
<oeCInNne>TestDrive class will havc a main) mcihou, anu iis solc
uiosc is io cicaic ol|ccis ol youi ncw iyc ihc noi-ihc-icsici class), anu
ihcn usc ihc uoi ociaioi .) io acccss ihc mcihous anu vaiiallcs ol ihc ncw
ol|ccis. This will all lc mauc siunningly clcai ly ihc lollowing cxamlcs.
Write your cIuss
class DogTestDrive {
public static void main (String[] args) {
// Dog test code goes here
}
}
-
-
-
-
-
- l
:
|.
]
-
-
-
-
::-
-
-
l
-
- -
.
-
-
::
CameLauncher
ra|r(3lr|r[| ars)
-
.
-
: .
6
-
-
::6
.
-
- -
-
:
l
.
-
l
-
||: l
l
- :l
.
-
l
6
.
-
-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
cIasses and objects
39
public class {
Player p1;
Player p2;
Player p3;
public void startGame() {
p1 = new Player();
p2 = new Player();
p3 = new Player();
int guessp1 = 0;
int guessp2 = 0;
int guessp3 = 0;
boolean p1isRight = false;
boolean p2isRight = false;
boolean p3isRight = false;
int targetNumber = (int) (Math.random() * 10);
System.out.println(I'm thinking of a number between 0 and 9...);
while(true) {
System.out.println(Number to guess is + targetNumber);
p1.guess();
p2.guess();
p3.guess();
guessp1 = p1.number;
System.out.println(Player one guessed + guessp1);
guessp2 = p2.number;
System.out.println(Player two guessed + guessp2);
guessp3 = p3.number;
System.out.println(Player three guessed + guessp3);
if (guessp1 == targetNumber) {
p1isRight = true;
}
if (guessp2 == targetNumber) {
p2isRight = true;
}
if (guessp3 == targetNumber) {
p3isRight = true;
}
if (p1isRight || p2isRight || p3isRight) {
System.out.println(We have a winner!);
System.out.println(Player one got it right? + p1isRight);
System.out.println(Player two got it right? + p2isRight);
System.out.println(Player three got it right? + p3isRight);
System.out.println(Game is over.);
break; // game over, so break out of the loop
} else {
// we must keep going because nobody got it right!
System.out.println(Players will have to try again.);
} // end if/else
} // end loop
} // end method
} // end class
6--::6.-- .: l--- -:l.-:-
.-.|-: -- l- l--- ||.]--
--:l:
:--.l- l--- ||.]-- --:l: .-
.::- l-- l- l- l--- ||.]--
-:l.-:- .-.|-:
-:|.-- l--- .-.|-: l- -| l-
l--- --::-: l- ||.]--: -.-
-:|.-- l--- .-.|-: l- -| . l--- --
.|:- .:- -- l- |.]--': .-:---
-.- . 'l.--l' ----- l.l l-
|.]--: .- l- --::
:.|| -.: |.]--': --::|` --l-
-l -.: |.]--': --:: |l- --:-|l - l--
--::|` --l- -----` ] .::-::- l-
----- .-.|- - -.: |.]--
:-: -.: |.]--': --:: l- :-- l -.l:-:
l- l.--l ----- | . |.]-- : -l,
l-- :-l l.l |.]--': .-.|- l- - l---
|-------, -- :-l l .|:- ] -.-|l`
|.]-- --- 6 |.]-- l-- 6 |.]-- l--- : -l
|l- || ---.l-- --.-: 6`
-l---:-, :l.] - l- |-- .- .: l-
|.]--: -- .--l-- --::
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
40 chapter 2
File Edit Window Help Explode
%java GameLauncher
I'm thinking of a number between 0 and 9...
Number to guess is 7
I'm guessing 1
I'm guessing 9
I'm guessing 9
Player one guessed 1
Player two guessed 9
Player three guessed 9
Players will have to try again.
Number to guess is 7
I'm guessing 3
I'm guessing 0
I'm guessing 9
Player one guessed 3
Player two guessed 0
Player three guessed 9
Players will have to try again.
Number to guess is 7
I'm guessing 7
I'm guessing 5
I'm guessing 0
Player one guessed 7
Player two guessed 5
Player three guessed 0
We have a winner!
Player one got it right? true
Player two got it right? false
Player three got it right? false
Game is over.
Dutput (it wiII be different each time you run it)
Kenn| n] !hc 0ecss| n] 0zmc
Guessing Game
public class Player {
int number = 0; // where the guess goes
public void guess() {
number = (int) (Math.random() * 10);
System.out.println(I'm guessing
+ number);
}
}
public class GameLauncher {
public static void main (String[] args) {
GuessGame game = new GuessGame();
game.startGame();
}
}
Juvu tukes out the
Surbuge
Lach time an ob|ect is created
in 1ava, it goes into an area of
memory known as 7he Heap.
All ob|ectsno matter when, where,
or how they're created - live on the
heap. 8ut it's not |ust any old memory
heap, the 1ava heap is actually called the
Carbage-CoIIectibIe Heap. when you
create an ob|ect, 1ava allocates memory
space on the heap according to how
much that particular ob|ect needs. An
ob|ect with, say, l5 instance variables,
will probably need more space than an
ob|ect with only two instance variables.
8ut what happens when you need to
reclaim that spaceI How do you get an
ob|ect out of the heap when you're done
with itI 1ava manages that memory
for you! when the 1vM can 'see' that an
ob|ect can never be used again, that
ob|ect becomes el||ole lot otooe
collect|on. And if you're running low on
memory, the Garbage Collector will run,
throw out the unreachable ob|ects, and
free up the space, so that the space can
be reused. |n later chapters you'll learn
more about how this works.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
cIasses and objects
41
8ll P0lk5
0ojecl-or|erled prorarr|r |els you exlerd
a prorar W|l|oul |av|r lo louc| prev|ous|y-
lesled, Wor||r code.
A|| Java code |s del|red |r a c|ass.
A c|ass descr|oes |oW lo ra|e ar oojecl ol
l|al c|ass lype. A c|ass |s ||ke a b|uepr|nt.
Ar oojecl car la|e care ol |lse|l, you dor'l
|ave lo |roW or care nou l|e oojecl does |l.
Ar oojecl knows l||rs ard does l||rs.
T||rs ar oojecl |roWs aooul |lse|l are ca||ed
|nstance var|ab|es. T|ey represerl l|e srare
ol ar oojecl.
T||rs ar oojecl does are ca||ed methods.
T|ey represerl l|e oenav|or ol ar oojecl.
w|er you creale a c|ass, you ray a|so Warl
lo creale a separale lesl c|ass W||c| you'||
use lo creale oojecls ol your reW c|ass lype.
A c|ass car |nher|t |rslarce var|ao|es ard
rel|ods lror a rore aoslracl superc|ass.
Al rurl|re, a Java prorar |s rol||r rore
l|ar oojecls 'la|||r' lo ol|er oojecls.
(-,- a,- |
oa|| qa--(:|-
What if I need gIobaI
variabIes and methods! How
do I do that if everything has to
go in a cIass!
There isn't a concept of
'global' variables and methods in
a 1ava OO program. |n practical
use, however, there are times
when you want a method (or
a constant) to be available
to any code running in any
part of your program. Think
of the random() method in
the Phrase-O-Matic app, it's a
method that should be callable
from anywhere. Or what about
a constant like |I ou'll learn
in chapter l0 that marking
a method as public and
static makes it behave much
like a 'global'. Any code, in any
class of your application, can
access a public static method.
And if you mark a variable as
public, static, and h nal
- you have essentially made a
globally-available constont.
7hen how is this object-
oriented if you can stiII make
gIobaI functions and gIobaI
data!
Pirst of all, everything
in 1ava goes in a class. So the
constant for | and the method
for random(), although both
public and static, are defined
within the Math class. And you
must keep in mind that these
static (global-like) things are the
exception rather than the rule
in 1ava. They represent a very
special case, where you don't
have multiple instances/ob|ects.
What is a 1ava program!
What do you actuaIIy Jeliver!
A 1ava program is a pile
of classes (or at least one class).
|n a 1ava application, one of
the classes must have a main
method, used to start-up the
program. So as a programmer,
you write one or more classes.
And those classes are what you
deliver. |f the end-user doesn't
have a 1vM, then you'll also
need to include that with
your application's classes,
so that they can run your
program. There are a number
of installer programs that
let you bundle your classes
with a variety of 1vM's (say, for
different platforms), and put it all
on a CD-POM. Then the end-user
can install the correct version of
the 1vM (assuming they don't
already have it on their machine.)
What if I have a hundred
cIasses! Dr a thousand! Isn't
that a big pain to deIiver
aII those individuaI Ies!
Can I bundIe them into one
Alicnrien 7hing!
es, it would be a big
pain to deliver a huge bunch of
individual files to your end-users,
but you won't have to. ou can
put all of your application files
into a 1ava Archive - o .jot l|le -
that's based on the pkzip format.
|n the |ar file, you can include
a simple text file formatted as
something called a mon|lest, that
defines which class in that |ar
holds the main() method that
should run.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
44 chapter 2
x 3
x 4
x < 4
x < 5
x > 0
x > l
our is to take code snippets from
the pool and place them into the
blank lines in the code. ou may
use the same snippet more than
once, and you won't need to use
all the snippets. our is to
make classes that will compile and
run and produce the output listed.
public class EchoTestDrive {
public static void main{String args| {
Echo el = new Echo{|,
_________________________
int x = 0,
while { ___________ | {
el.hello{|,
__________________________
if { ____________ | {
e2.count = e2.count + l,
}
if { ____________ | {
e2.count = e2.count + el.count,
}
x = x + l,
}
System.out.println{e2.count|,
}
}
class ____________ {
int _________ = 0,
void ___________ {
System.out.println{"helloooo... "|,
}
}
Note: ach snippet
from the pooI can be
used more than oncel
File Edit Window Help mplode
%java EchoTestDrive
helloooo...
helloooo...
helloooo...
helloooo...
10
Dutput
el el + l,
el count + l,
el.count count + l,
el.count el.count + l,
e2 el,
Lcho e2,
Lcho e2 el,
Lcho e2 new Lcho( ),
x
y
e2
count
Lcho
Tester
echo( )
count( )
hello( )
onus uestion l
|f the last line of output was
24 instead of 10 how would
you complete the puzzle I
puzzIe: PooI PuzzIe
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
cIasses and objects
45
Code Mognefs:
File Edit Window Help Dance
% java DrumKitTestDrive
bang bang ba-bang
ding ding da-ding
class DrumKit {
boolean topHat = true,
boolean snare = true,
void playTopHat{| {
System.out.println{"ding ding da~ding"|,
}
void playSnare{| {
System.out.println{"bang bang ba~bang"|,
}
}
class DrumKitTestDrive {
public static void main{String args| {
DrumKit d = new DrumKit{|,
d.playSnare{|,
d.snare = false,
d.playTopHat{|,
if {d.snare == true| {
d.playSnare{|,
}
}
}
class TapeDeck {
boolean canRecord = false,
void playTape{| {
System.out.println{"tape playing"|,
}
void recordTape{| {
System.out.println{"tape recording"|,
}
}
class TapeDeckTestDrive {
public static void main{String args| {
TupeDeck t = new TupeDeck{ };
t.canRecord = true,
t.playTape{|,
if {t.canRecord == true| {
t.recordTape{|,
}
} We've got the tempIute now we huve
} to muke un object |
class DVDPlayer {
boolean canRecord = false,
void recordDVD{| {
System.out.println{"DVD recording"|,
}
void pIuyDVD { } {
System,out,printIn{"DVD pIuying"};
}
}
class DVDPlayerTestDrive {
public static void main{String args| {
DVDPlayer d = new DVDPlayer{|,
d.canRecord = true,
d.playDVD{|,
if {d.canRecord == true| {
d.recordDVD{|,
}
} The Iine: d,pIuyDVD{ }; wouIdn't
} compiIe without u method |
]e;ejze o|ajoz
8e fhe CompiIer:
exercise soIutions
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
cIasses and objects
47
public class EchoTestDrive {
public static void main{String args| {
Echo el = new Echo{|,
Echo eZ ~ new Echo( ), // fhe correcf onswer
- or -
Echo eZ ~ eI, // is fhe bonus onswerl
int x = 0,
while { x 4 | {
el.hello{|,
eI.counf ~ eI.counf + I,
if { x ~~ 3 | {
e2.count = e2.count + l,
}
if { x 0 | {
e2.count = e2.count + el.count,
}
x = x + l,
}
System.out.println{e2.count|,
}
}
class Echo {
int counf = 0,
void heIIo( ) {
System.out.println{"helloooo... "|,
}
}
File Edit Window Help Assimilate
%java EchoTestDrive
helloooo...
helloooo...
helloooo...
helloooo...
10
I am compiIed from a .java fiIe.
My instance variabIe vaIues can be
different from my buddy's vaIues.
I behave Iike a tempIate.
I Iike to do stuff.
I can have many methods.
I represent 'state'.
I have behaviors.
I am Iocated in objects.
I Iive on the heap.
I am used to create object
instances.
My state can change.
I decIare methods.
I can change at runtime.
:|.::
--:l
:|.::
--:l, --l-
:|.::, --:l
-:l.-:- .-.|-
--:l, :|.::
--l-, -:l.-:- .-.|-
--:l
:|.::
--:l, -:l.-:- .-.|-
:|.::
--:l, -:l.-:- .-.|-
ygo m J/
Mofe: bofh cIosses ond objecfs ore soid fo hove sfofe ond behovior.
They're defned in fhe cIoss, buf fhe objecf is oIso soid fo 'hove'
fhem. Pighf now, we don'f core where fhey fechnicoIIy Iive.
]azz|e o|ajoz
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
3 primitives and references
this is a new chapter 49
VariabIes come in two fIavors: primitive and reference. So far you've
used variables in two placesas ob|ect state (instance variables), and as IocaI variables
(variables declared within a methoJ). Later, we'll use variables as arguments (values sent to a
method by the calling code), and as return types (values sent back to the caller of the method).
ou've seen variables declared as simple primitive integer values (type ). ou've seen
variables declared as something more compIex like a String or an array. 8ut there's gotta be
more to Iife than integers, Strings, and arrays. what if you have a PetOwner ob|ect with a Dog
instance variableI Or a Car with an LngineI |n this chapter we'll unwrap the mysteries of 1ava
types and look at what you can Jeclote as a variable, what you can ut in a variable, and what you
can Jo with a variable. And we'll finally see what life is ttuly like on the garbage-collectible heap.
Know Your Variables
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
50 chapter 3
decIaring a variabIe
Pcr|zr|n] z vzr|z||c
]ava carcs about typc. Ii won`i lci you uo
somcihing lizaiic anu uangcious liIc siull a
Giiallc iclcicncc inio a Rallii vaiiallc-whai
hacns whcn somconc iiics io asI ihc so-callcu
Fnbb. io . Anu ii won`i lci you ui a
uoaiing oini numlci inio an inicgci vaiiallc,
unlcss you nIrowIeJe o Le o.Ie. ihai you
Inow you mighi losc iccision liIc, cvciyihing
alici ihc uccimal oini).
Thc comilci can soi mosi iollcms:
Rabbit hopper = new Giraffe();
Don`i cxcci ihai io comilc. TLnrIuII,.
Ioi all ihis iyc-salciy io woiI, you musi ucclaic
ihc iyc ol youi vaiiallc. Is ii an inicgci. a Dog.
A singlc chaiacici. Vaiiallcs comc in iwo uavois:
primitive anu object re[erence. Piimiiivcs holu
lunuamcnial valucs ihinI: simlc lii aiicins)
incluuing inicgcis, loolcans, anu uoaiing oini
numlcis. Ol|cci iclcicnccs holu, wcll, .ee.ere
io obe gcc, uiun`i Ln clcai ii u.)
Wc`ll looI ai iimiiivcs hisi anu ihcn movc
on io whai an ol|cci iclcicncc ically mcans.
Bui icgaiulcss ol ihc iyc, you musi lollow iwo
ucclaiaiion iulcs:
Bcsiucs a iyc, a vaiiallc nccus a namc, so ihai
you can usc ihai namc in couc.
variabIes must have a type
int count;
l]- -.--
).. :.--: .--l l]-
/
-- :.-'l -l . 6
-.-
- .
.l .-.|-
variabIes must have a name
Noic: Whcn you scc a siaicmcni liIc: an ol|cci
ol typc X", ihinI ol ,e anu In as synonyms.
Wc`ll ichnc ihai a liiilc moic in laici chaicis.)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
primitives and references
51
|4 ||kc z 4ee||c merhz, ne, mzkc | ! zn |n!.
Whcn you ihinI ol ]ava vaiiallcs, ihinI ol cus. Collcc cus, ica cus, giani
cus ihai holu lois anu lois ol lcci, ihosc lig cus ihc ocoin comcs in ai
ihc movics, cus wiih cuivy, scxy hanulcs, anu cus wiih mciallic iiim ihai
you lcaincu can ncvci, cvci go in ihc miciowavc.
A variablc is just a cup. A containcr. It hoIds somcthing.
Ii has a sizc, anu a iyc. In ihis chaici, wc`ic going io looI hisi ai ihc
vaiiallcs cus) ihai holu primitivcs, ihcn a liiilc laici wc`ll looI ai cus
ihai holu .ee.ere o obe. Siay wiih us hcic on ihc wholc cu analogy-as
simlc as ii is iighi now, ii`ll givc us a common way io looI ai ihings whcn
ihc uiscussion gcis moic comlcx. Anu ihai`ll hacn soon.
Piimiiivcs aic liIc ihc cus ihcy havc ai ihc collcchousc. Il you`vc lccn io a
SiailucIs, you Inow whai wc`ic ialIing aloui hcic. Thcy comc in uillcicni
sizcs, anu cach has a namc liIc shoii`, iall`, anu, I`u liIc a
gianuc` mocha hall-call wiih cxiia whicu cicam".
You mighi scc ihc cus uislaycu on ihc counici,
so you can oiuci aioiiaicly:
Anu in ]ava, iimiiivcs comc in uillcicni sizcs, anu ihosc sizcs
havc namcs. Whcn you ucclaic a vaiiallc in ]ava,
you musi ucclaic ii wiih a sccihc iyc. Thc
loui coniaincis hcic aic loi ihc loui
inicgci iimiiivcs in ]ava.
Each cu holus a valuc, so loi ]ava iimiiivcs, iaihci ihan saying, I`u liIc a
iall licnch ioasi", you say io ihc comilci, I`u liIc an ini vaiiallc wiih ihc
numlci 90 lcasc." Excci loi onc iiny uillcicncc... in ]ava you also havc io
givc youi cu a rne. So ii`s aciually, I`u liIc an ini lcasc, wiih ihc valuc
ol 24S6, anu namc ihc vaiiallc height." Each iimiiivc vaiiallc has a hxcu
numlci ol liis cu sizc). Thc sizcs loi ihc six numciic iimiiivcs in ]ava
aic shown lclow:
smoII shorf foII gronde
Iong inf shorf byfe
byfe shorf inf Iong oof doubIe
Type 8|l 0epl| va|ue Rare
boolean and char
boolean (1vM-specific) or
char l6 bits 0 to 65535
numeric {all are signed}
integer
byte 8 bits -l28 to l27
short l6 bits -32768 to
32767
int 32 bits -2l47483648
to 2l47483647
long 64 bits -huge to huge
hoating point
float 32 bits varies
double 64 bits varies
Primitive declarations
with assignments:
int x,
x 234,
byte b 89,
boolean isPun true,
double d 3456.98,
char c 'f',
int z x,
boolean isPunkPock,
isPunkPock false,
boolean powerOn,
powerOn isPun,
long big 3456789,
float f 32.5f,
N-l- l- '' 6-ll. .- l.l
-l . |-.l, -:.-:- ).. l-:
.-]l- -l . |-.l- --l :
. --|-, --|-:: ]-- -:- ''
Primitive Types
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
52 chapter 3
primitive assignment
Yee rcz||y 4en! wzn! !e sp||| !hz!...
Bc surc thc valuc can ht into thc variablc.
You can`i ui a laigc valuc inio a
small cu.
Wcll, OK, you can, lui you`ll
losc somc. You`ll gci, as wc say,
.IIne. Thc comilci iiics io
hcl icvcni ihis il ii can icll
liom youi couc ihai somcihing`s
noi going io hi in ihc coniainci
vaiiallc/cu) you`ic using.
Ioi cxamlc, you can`i oui an
ini-lull ol siull inio a lyic-sizcu
coniainci, as lollows:
int x = 24;
byte b = x;
//won't work!!
Why uocsn`i ihis woiI, you asI. Alici all, ihc valuc ol : is 24, anu 24 is uchniicly
small cnough io hi inio a lyic. You Inow ihai, anu we Inow ihai, lui all ihc
comilci caics aloui is ihai you`ic iiying io ui a lig ihing inio a small ihing,
anu ihcic`s ihc o.b.I., ol silling. Don`i cxcci ihc comilci io Inow whai ihc
valuc ol : is, cvcn il you hacn io lc allc io scc ii liicially in youi couc.
You can assign a valuc to a variablc in onc oI scvcral ways including:
iyc a I.e.nI valuc alici ihc cquals sign x, isGoou , cic.)
assign ihc valuc ol onc vaiiallc io anoihci x y)
usc an cxicssion comlining ihc iwo x y + )
In ihc cxamlcs lclow, ihc liicial valucs aic in lolu iialics:
int size = 32; dec|are ar |rl rared s|ze, ass|r |l l|e va|ue J2
char initial = `j'; dec|are a c|ar rared |n|r|a|, ass|r |l l|e va|ue 'j
double d = 456.709; dec|are a douo|e rared o, ass|r |l l|e va|ue 456.709
boolean isCrazy; dec|are a ooo|ear rared |s0razy (ro ass|rrerl)
isCrazy = true; ass|r l|e va|ue rrue lo l|e prev|ous|y-dec|ared |s0razy
int y = x + 456; dec|are ar |rl rared y, ass|r |l l|e va|ue l|al |s l|e sur
ol W|alever x |s roW p|us 456
+,-+ :+ ,-+:.|
The compiler won't let you put
a value from a large cup into
a small one. 8ut what about
the other waypouring a
small cup into a big oneI Ne
reblem.
8ased on what you know
about the size and type of the
primitive variables, see if you
can figure out which of these
are legal and which aren't.
we haven't covered all the
rules yet, so on some of these
you'll have to use your best
|udgment. 7i: The compiler
always errs on the side of
safety.
Prom the following list, Circle
the statements that would be
legal if these lines were in a
single method:
1. int x = 34.5;
2. boolean boo = x;
3. int g = 17;
4. int y = g;
5. y = y + 10;
6. short s;
7. s = y;
8. byte b = 3;
9. byte v = b;
10. short n = 12;
11. v = n;
12. byte k = 128;
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
primitives and references
53
M
.
-
l
l
:
e C
areful!
ears Shouldn't Ingest Large
Furry D
ogs
ll you m
ole u yout own, |tll st|cl even oettet.
8_ C_ 8_ 5_ l_ l_ l_ 0_
Bzrk zwzy frem !hz! kcywer4|
You Inow you nccu a namc anu a iyc loi youi vaiiallcs.
You alicauy Inow ihc iimiiivc iycs.
But whot con you use os nomes Thc iulcs aic simlc. You
can namc a class, mcihou, oi vaiiallc accoiuing io ihc
lollowing iulcs ihc ical iulcs aic slighily moic ucxillc,
lui ihcsc will Icc you salc):
t must start with a letter, underscore {_}, or
dollar sign {S}. You can't start a name with a
number.
After the hrst character, you can use numbers as
well. Just don't start it with a number.
t can be anything you like, sub]ect to those two
rules, ]ust so long as it isn't one of Java's reserved
words.
aic Icywoius anu oihci ihings) ihai ihc comilci iccognizcs.
Anu il you ically wani io lay conlusc-a-comilci, ihcn |usi .,
using a icscivcu woiu as a namc.
You`vc alicauy sccn somc icscivcu woius whcn wc looIcu ai
wiiiing oui hisi main class:
public static void
Anu ihc iimiiivc iycs aic icscivcu as wcll:
boolean char byte short int long oat double
Bui ihcic aic a loi moic wc havcn`i uiscusscu yci. Evcn il you uon`i
nccu io Inow whai ihcy mcan, you siill nccu io Inow you can`i usc
cm youiscll. Do not-urJe. nr, ..unre-try to memorize these
now. To maIc ioom loi ihcsc in youi hcau, you`u iolally havc io
losc somcihing clsc. IiIc whcic youi cai is aiIcu. Don`i woiiy, ly
ihc cnu ol ihc looI you`ll havc mosi ol ihcm uown colu.
-
-
'l
-
:-
.
-
]
-
-
:-
-
-
]
-
-
-
-
-
-
-
.
-
-
:
|eeleer ||e tler iet|le Kee| ir| lerj :ler| jt|lit jrire|e
jre|et|ei e|:|ret| lrel re|ire :|e|it :|rit|lj :rtlreritei |rer:ier| rele|ile il
el:e ie wlile :wi|tl te:e ieletl| ler |reel ter|irte e::er|
tle:: et|eri: imjlemer|: imjer| ir:|erteel ir|erlete rew jetleje :tjer |li:
te|tl lrell |r |lrew |lrew: re|trr reii ter:| je|e ertm
Ih|s !z||c rcscrvc4.
Java's keywords and other reserved words (in no useful order). f you use these for names, the compiler will be very, upset.
Mo moffer whof
you heor, do nof, I repeof,
do Ief me ingesf
onofher Iorge furry dog.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
54 chapter 3
object references
0en!re|||n] yeer Pe] e|jcr!
You Inow how io ucclaic a iimiiivc vaiiallc anu assign ii a
valuc. Bui now whai aloui non-iimiiivc vaiiallcs. In oihci
woius, wLn nbou obe:
There is actuaIIy no such thing as an object variabIe.
There's onIy an object reference variabIe.
An object reference variabIe hoIds bits that represent a
way to access an object.
It doesn't hoId the object itseIf, but it hoIds something
Iike a pointer. Or an address. Except, in Java we don't
reaIIy know what is inside a reference variabIe. We do
know that whatever it is, it represents one and onIy one
object. And the JVM knows how to use the reference to
get to the object.
You can`i siull an ol|cci inio a vaiiallc. Wc olicn ihinI ol
ii ihai way... wc say ihings liIc, I asscu ihc Siiing io ihc
Sysicm.oui.iiniln) mcihou." Oi, Thc mcihou iciuins a Dog",
oi, I ui a ncw Ioo ol|cci inio ihc vaiiallc namcu myIoo."
Bui ihai`s noi whai hacns. Thcic aicn`i giani
cxanuallc cus ihai can giow io ihc sizc ol any
ol|cci. Ol|ccis livc in onc lacc anu onc lacc
only-ihc gailagc collcciillc hca! You`ll
lcain moic aloui ihai laici in ihis chaici.)
Alihough a iimiiivc vaiiallc is lull ol
liis icicscniing ihc aciual voIue ol ihc
vaiiallc, an ol|cci iclcicncc vaiiallc is lull
ol liis icicscniing o woy to get to the
object.
You usc ihc uoi ociaioi .)
on a iclcicncc vaiiallc io say,
usc ihc ihing beo.e ihc uoi io
gci mc ihc ihing ne. ihc uoi." Ioi
cxamlc:
myDog.bark();
mcans, usc ihc ol|cci iclcicnccu ly ihc vaiiallc myDog io
invoIc ihc laiI) mcihou." Whcn you usc ihc uoi ociaioi on
an ol|cci iclcicncc vaiiallc, ihinI ol ii liIc icssing a luiion
on ihc icmoic coniiol loi ihai ol|cci.
Dog d = new Dog{};
d.bark{};
l- - l:
|- l:
1- - . l-
------:- .-.|- .:
. l- ----l- :--l--|
/-- -:- l l- -l l-
--:l l- - :---l-
|--- --l-:`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
primitives and references
55
reference byfe shorf inf Iong
& I JZ 1 [|i| iej|l re| relerer|]
n e|jcr! rcfcrcnrc |s jes!
zne!hcr vzr|z||c vz|ec.
Something that goes in a cup.
DnIy this time, the vaIue is a remote controI.
Wi|h primi|ive voriobles, |he volue ol |he vori
oble is... |he volue (5, 2.Z, 'o).
Wi|h relerence voriobles, |he volue ol |he
vorioble is... bils represenling o woy lo gel lo
o specihc obecl.
You don| know (or core) how ony por|iculor
1VN implemen|s ob[ec| relerences. 5ure, |hey
migh| be o poin|er |o o poin|er |o... bu| even
il you know, you s|ill con| use |he bi|s lor
ony|hing o|her |hon occessing on ob[ec|.
Dog myDog = new Dog();
Tells the 1vM to allocate space for a
reference variable, and names that
variable . The reference variable
is, forever, of type Dog. |n other words,
a remote control that has buttons to
control a Dog, but not a Cat or a 8utton
or a Socket.
DecIore o reference
voriobIe
Dog
m9ej
Dog myDog = new Dog();
Tells the 1vM to allocate space for a
new Dog ob|ect on the heap (we'll
learn a lot more about that process,
especially in chapter 9.)
Creofe on objecf
Dog myDog = new Dog();
The 3 steps of ob]ect
declaration, creation and
assignment
1
2
3
Dog objecf
Dog myDog = new Dog();
Assigns the new Dog to the reference
variable myDog. |n other words,
regrnms rhe remere cenrrel.
Can I do arithmetic on a
reference variabIe, increment it,
you know - C stuff!
Nope. Say it with me again,
"1ava is not C.
object references
HeadFirst: So, tell us, what`s lile like lor an object relerence?
Reference: Fretty simple, really. I`m a remote control ano I can be programmeo to
control oillerent objects.
HeadFirst: Do you mean oillerent objects even while you`re running? Like, can you
reler to a Dog ano then nve minutes later reler to a Car?
Reference: Ol course not. Once I`m oeclareo, that`s it. Il I`m a Dog remote control
then I`ll never be able to point ,oops my bao, we`re not supposeo to say iot, I mean r.f.r
to anything but a Dog.
HeadFirst: Does that mean you can reler to only one Dog?
Reference: No. I can be relerring to one Dog, ano then nve minutes later I can reler to
some t/.r Dog. As long as it`s a Dog, I can be reoirecteo ,like reprogramming your remote
to a oillerent TV, to it. Unless... no never mino.
HeadFirst: No, tell me. What were you gonna say?
Reference: I oon`t think you want to get into this now, but I`ll just give you the short
version il I`m markeo as , then once I am assigneo a Dog, I can never be repro-
grammeo to anything else but t/ot one ano only Dog. In other woros, no other object can
be assigneo to me.
HeadFirst: You`re right, we oon`t want to talk about that now. OK, so unless you`re
, then you can reler to one Dog ano then reler to a oillerent Dog later. Can you ever
reler to ot/io ot oll? Is it possible to not be programmeo to anything?
Reference: Yes, but it oisturbs me to talk about it.
HeadFirst: Why is that?
Reference: Because it means I`m , ano that`s upsetting to me.
HeadFirst: You mean, because then you have no value?
Reference: Oh, i a value. I`m still a remote control, but it`s like you brought
home a new universal remote control ano you oon`t have a TV. I`m not programmeo to
control anything. They can press my buttons all oay long, but nothing gooo happens. I
just leel so... useless. A waste ol bits. Granteo, not that many bits, but still. Ano that`s not
the worst part. Il I am the only relerence to a particular object, ano then I`m set to
,oeprogrammeo,, it means that now ooo, can get to that object I hao been relerring to.
HeadFirst: Ano that`s bao because...
Reference: You have to o/? Here I`ve oevelopeo a relationship with this object, an
intimate connection, ano then the tie is suooenly, cruelly, severeo. Ano I will never see
that object again, because now it`s eligible lor |prooucer, cue tragic music| oroo. cll.ctio.
Snill. But oo you think programmers ever consioer t/ot? Snil. Why, o/, can`t I be a primi-
tive? I /ot. o.io o r.f.r.oc.. The responsibility, all the broken attachments...
This week's interview:
Object Reference
1a-a spese3
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
primitives and references
57
8ook
8
o
o
k
ob
j
e
c
f
8
o
o
k
ob
j
e
c
f
8ook
8
o
o
k
ob
j
e
c
f
8
o
o
k ob
j
e
c
f
8ook
8ook
c = b;
Assign the value of variable to
variable . 8y now you know what
this means. The bits inside variable
are copied, and that new copy is
stuffed into variable .
Both b and c refer to the
same ob]ect.
Peferences: 3
Ob|ects: 2
8ook
8
o
ok o
b
j
e
c
f
8
o
o
k ob
j
e
c
f
8
o
o
k
ob
j
e
c
f
8
o
o
k
ob
j
e
c
f
8ook
8
o
o
k ob
j
e
c
f
8ook
c = null;
Assign the value to variable .
This makes a null teletence, meaning
it doesn't refer to anything. 8ut it's still
a reference variable, and another 8ook
ob|ect can still be assigned to it.
Ob]ect 2 still has an active
reference {b}, and as long
as it does, the ob]ect is not
eligible for GC.
Active Peferences: l
null Peferences: l
Peachable Ob|ects: l
Abandoned Ob|ects: l
I|fc zn4 4cz!h en !hc hczp
g
a
r
b
a
g
e
c
o
l
l
e
c
t
i
b
l
e
h
e
a
p
g
a
r
b
a
g
e
c
o
l
l
e
c
t
i
b
l
e
h
e
a
p
g
a
r
b
a
g
e
c
o
l
l
e
c
t
i
b
l
e
h
e
a
p
objects on the heap
1: -] : l-.:l
.-.-~:-||-:l-- .l
8
o
o
k ob
j
e
c
f
8ook
l|| l-.:l
8ook
--|| ------:-
|--l ---.--- l- .-]l-`
8
o
o
k
ob
j
e
c
f
8
o
o
k
ob
j
e
c
f
I
I
Z
Z
Z
I
N-l ]-l l-.:l
|:.- .: |-- .:
----: l- l`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
primitives and references
59
rrzys zrc e|jcr!s !ee
Thc ]ava sianuaiu liliaiy incluucs
lois ol sohisiicaicu uaia siiuciuics
incluuing mas, iiccs, anu scis
scc Acnuix B), lui aiiays aic
gicai whcn you |usi wani a quicI,
oiucicu, clhcicni lisi ol ihings.
Aiiays givc you lasi ianuom
acccss ly lciiing you usc an inucx
osiiion io gci io any clcmcni in
ihc aiiay.
Evciy clcmcni in an aiiay is |usi
a vaiiallc. In oihci woius, onc ol
ihc cighi iimiiivc vaiiallc iycs
ihinI: Iaigc Iuiiy Dog) oi a
iclcicncc vaiiallc. Anyihing you
woulu ui in a .n..nbIe ol ihai iyc
can lc assigncu io an n..n, eIeer
ol ihai iyc. So in an aiiay ol iyc
ini ini]|), cach clcmcni can holu
an ini. In a Dog aiiay Dog]|) cach
clcmcni can holu... a Dog. No,
icmcmlci ihai a iclcicncc vaiiallc
|usi holus a iclcicncc a icmoic
coniiol), noi ihc ol|cci iiscll. So
in a Dog aiiay, cach clcmcni can
holu a .eoe or.oI io a Dog. Ol
couisc, wc siill havc io maIc ihc
Dog ol|ccis... anu you`ll scc all ihai
on ihc ncxi agc.
Bc suic io noiicc onc Icy ihing
in ihc iciuic alovc - Le n..n, .
nr obe, e.er LouL .` nr n..n, o
.....e.
Arrays arc always objccts, whcthcr
thcy'rc dcclarcd to hold primitivcs
or objcct rcIcrcnccs. Bui you can
havc an aiiay ol|cci ihai`s ucclaicu
io LoIJ iimiiivc valucs. In oihci
woius, ihc aiiay ol|cci can havc
eIeer which aic iimiiivcs, lui
ihc aiiay iiscll is re.e. a iimiiivc.
Rcgaiulcss ol whai ihc aiiay holus,
ihc aiiay iiscll is always an ol|cci!
inf orroy objecf (inf[])
inf[]
nums[0] = 6;
nums[1] = 19;
nums[2] = 44;
nums[3] = 42;
nums[4] = 10;
nums[5] = 20;
nums[6] = 1;
-
l
.
-
|
-
:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
60 chapter 3
Dog orroy objecf (Dog[])
Dog[]
rare
oar|()
eal()
c|aseCal()
0en!re| yeer Pe]
|w| !h z rcfcrcnrc vzr|z||cI
Dog do = new Dog();
do.name = Fido;
D
og ob
j
e
c
f
rare
oar|()
eal()
c|aseCal()
Pe] crzmp|c
File Edit Window Help Howl
%java Dog
null says Ruff!
last dog's name is Bart
Fred says Ruff!
Marge says Ruff!
Bart says Ruff!
8ll P0lk5
var|ao|es core |r lWo l|avors: pr|r|l|ve ard
relererce.
var|ao|es rusl a|Ways oe dec|ared W|l| a rare
ard a lype.
A pr|r|l|ve var|ao|e va|ue |s l|e o|ls represerl|r
l|e va|ue (5, 'a', lrue, 3.111, elc.).
A relererce var|ao|e va|ue |s l|e o|ls
represerl|r a Way lo el lo ar oojecl or l|e
|eap.
A relererce var|ao|e |s |||e a rerole corlro|.
us|r l|e dol operalor (.) or a relererce
var|ao|e |s |||e press|r a oullor or l|e rerole
corlro| lo access a rel|od or |rslarce var|ao|e.
A relererce var|ao|e |as a va|ue ol null W|er
|l |s rol relererc|r ary oojecl.
Ar array |s a|Ways ar oojecl, ever |l l|e array
|s dec|ared lo |o|d pr|r|l|ves. T|ere |s ro suc|
l||r as a pr|r|l|ve array, or|y ar array l|al
pr|r|l|ves.
.--.]: .- . .-.|- '|--l'
l.l -: ]-- l- ----- -
-|----l: - l- .--.]
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
primitives and references
63
[ze[ | ([ ]zvz |j], n ([j, zg
,n(, z e]( ,ae |j].
(a j j, ( ]zy ej] zn]
](jn w[([ ze[ | ([, |j],
wj]] ej]. ]| ([y wn'(
ej], [w wa]] ya
|jy ([/
class Books {
String title,
String author,
}
class BooksTestDrive {
public static void main{String args| {
Books myBooks = new Books3,
int x = 0,
myBooks0.title = "The Grapes of Java",
myBooksl.title = "The Java Gatsby",
myBooks2.title = "The Java Cookbook",
myBooks0.author = "bob",
myBooksl.author = "sue",
myBooks2.author = "ian",
while {x < 3| {
System.out.print{myBooksx.title|,
System.out.print{" by "|,
System.out.println{myBooksx.author|,
x = x + l,
}
}
}
class Hobbits {
String name,
public static void main{String args| {
Hobbits h = new Hobbits3,
int z = 0,
while {z < 4| {
z = z + l,
hz = new Hobbits{|,
hz.name = "bilbo",
if {z == l| {
hz.name = "frodo",
}
if {z == 2| {
hz.name = "sam",
}
System.out.print{hz.name + " is a "|,
System.out.println{"good Hobbit name"|,
}
}
}
] ge eomgj|e;
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
64 chapter 3
A working 1ava program is all scrambled up
on the fridge. Can you reconstruct the code
snippets to make a working 1ava program
that produces the output listed belowI
Some of the curly braces fell on the floor
and they were too small to pick up, so feel
free to add as many of those as you need!
islands0 = "Bermuda", islandsl = "Fii",
islands2 = "Azores", islands3 = "Cozumel",
class TestArrays {
public static void main{String args| {
int ref,
while {y < 4| {
String islands = new String4,
System.out.print{"island = "|,
int index = new int4,
System.out.println{islandsref|,
File Edit Window Help Bikini
% java TestArrays
island = Fiji
island = Cozumel
island = Bermuda
island = Azores
index0 = l,
indexl = 3,
index2 = 0,
index3 = 2,
y = y + l,
int y = 0,
ref = indexy,
CaJe Kagaets
exercise: Code Magnets
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
primitives and references
65
x x + l,
x x + 2,
x x - l,
x < 4
x < 5
our is to take code snippets from
the pool and place them into the
blank lines in the code. ou may
use the same snippet more than
once, and you won't need to use
all the snippets. our is to
make a class that will compile and
run and produce the output listed.
class Triangle {
double area,
int height,
int length,
public static void main{String args| {
____________
_______________________
while { __________ | {
__________________________
________.height = {x + l| * 2,
________.length = x + 4,
__________________________
System.out.print{"triangle "+x+", area"|,
System.out.println{" = " + _______.area|,
________________
}
______________
x = 27,
Triangle t5 = ta2,
ta2.area = 343,
System.out.print{"y = " + y|,
System.out.println{", t5 area = "+ t5.area|,
}
void setArea{| {
____________ = {height * length| / 2,
}
}
Note: ach snippet
from the pooI can be
used more than oncel
File Edit Window Help Bermuda
%java Triangle
triangle 0, area = 4.0
triangle 1, area = 10.0
triangle 2, area = 18.0
triangle 3, area = ____
y = ______________________
Dutput
Triangle | | ta new Triangle(4),
Triangle ta new | | Triangle|4|,
Triangle | | ta new Triangle|4|,
ta new Triangle(),
ta|x| new Triangle(),
ta.x new Triangle(),
ta|x| setArea(),
ta.x setArea(),
ta|x|.setArea(),
int x,
int y,
int x 0,
int x l,
int y x,
area
ta.area
ta.x.area
ta|x|.area
ta.x
ta(x)
ta|x|
x
y
onus uestionl
Por extra bonus points, use snippets
from the pool to fill in the missing
output (above).
28.0
30.0
4, t5 area l8.0
4, t5 area 343.0
27, t5 area l8.0
27, t5 area 343.0
|---l--: -- --'l -:- . :-.-.l-
l-:l :|.::, -:.-:- --'-- l-]- l-
:.- :.:- -- l- .-`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
66 chapter 3
A short 1ava program is listed to the
right. when '// do stuff' is reached, some
ob|ects and some reference variables
will have been created. our task is
to determine which of the reference
variables refer to which ob|ects. Not all
the reference variables will be used, and
some ob|ects might be referred to more
than once. Draw lines connecting the
reference variables with their matching
ob|ects.
Unless you're way smarter than us,
you probably need to draw diagrams
like the ones on page 55 and 56 of this
chapter. Use a pencil so you can draw
and then erase reference links (the
arrows going from a reference remote
control to an ob|ect).
4 Heap o' 1roub|e
-.l: -.: ------:-
.-.|- -l -.l:-
--:l|:`
/-- -l --l .- l-
-:- ---] ------:-
Reference VariabIes: Heapuiz Dbjects:
class HeapQuiz {
int id = 0;
public static void main(String [] args) {
int x = 0;
HeapQuiz [ ] hq = new HeapQuiz[5];
while ( x < 3 ) {
hq[x] = new HeapQuiz();
hq[x].id = x;
x = x + 1;
}
hq[3] = hq[1];
hq[4] = hq[1];
hq[3] = null;
hq[4] = hq[0];
hq[0] = hq[3];
hq[3] = hq[2];
hq[2] = hq[0];
// do stuff
}
}
hq[0]
hq[I]
hq[Z]
hq[3]
hq[4]
puzzIe: Heap o' TroubIe
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
primitives and references
67
The case of the pilfered references
It was a dark and stormy night. Tawny strolled into the programmers` bullpen like she
owned the place. She knew that all the programmers would still be hard at work, and she
wanted help. She needed a new method added to the pivotal class that was to be loaded into the
client`s new top-secret Java-enabled cell phone. Heap space in the cell phone`s memory was
as tight as Tawny`s top, and everyone knew it. The normally raucous buzz in the bullpen Iell to
silence as Tawny eased her way to the white board. She sketched a quick overview oI the new
method`s Iunctionality and slowly scanned the room. 'Well boys, it`s crunch time, she purred.
'Whoever creates the most memory eIfcient version oI this method is coming with me to the
client`s launch party on Maui tomorrow... to help me install the new soItware.
The next morning Tawny glided into the bullpen wearing her short Aloha dress.
'Gentlemen, she smiled, 'the plane leaves in a Iew hours, show me what you`ve
got!. Bob went frst; as he began to sketch his design on the white board Tawny
said, 'Let`s get to the point Bob, show me how you handled updating the list oI con-
tact objects. Bob quickly drew a code Iragment on the board:
Contact [] ca = new Contact[10];
while ( x < 10 ) { // make 10 contact objects
ca[x] = new Contact();
x = x + 1;
}
// do complicated Contact list updating stuff with ca
'Tawny I know we`re tight on memory, but your spec said that we had to be able to access
individual contact inIormation Ior all ten allowable contacts, this was the best scheme I could
cook up, said Bob. Kent was next, already imagining coconut cocktails with Tawny, 'Bob,
he said, 'your solution`s a bit kludgy don`t you think? Kent smirked, 'Take a look at this
baby:
Contact refc;
while ( x < 10 ) { // make 10 contact objects
refc = new Contact();
x = x + 1;
}
// do complicated Contact list updating stuff with refc
'I saved a bunch oI reIerence variables worth oI memory, Bob-o-rino, so put away your
sunscreen, mocked Kent. 'Not so Iast Kent!, said Tawny, 'you`ve saved a little memory, but
Bob`s coming with me..
Why did 1awny choose Bob's method over Kent's, when Kent's used less memory?
]Jc_Jna[c
_s[ci
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
68 chapter 3
A
Code Mognefs:
class Books {
String title,
String author,
}
class BooksTestDrive {
public static void main{String args| {
Books myBooks = new Books3,
int x = 0,
myooks[0j = new ooks{}; Pemember: We huve to
myooks[1j = new ooks{}; uctuuIIy muke the ooks
myooks[Zj = new ooks{}; objects |
myBooks0.title = "The Grapes of Java",
myBooksl.title = "The Java Gatsby",
myBooks2.title = "The Java Cookbook",
myBooks0.author = "bob",
myBooksl.author = "sue",
myBooks2.author = "ian",
while {x < 3| {
System.out.print{myBooksx.title|,
System.out.print{" by "|,
System.out.println{myBooksx.author|,
x = x + l,
}
}
}
class Hobbits {
String name,
public static void main{String args| {
Hobbits h = new Hobbits3,
int z = -1; Pemember: urruys sturt with
whiIe {z - Z} { eIement 0 |
z = z + l,
hz = new Hobbits{|,
hz.name = "bilbo",
if {z == l| {
hz.name = "frodo",
}
if {z == 2| {
hz.name = "sam",
}
System.out.print{hz.name + " is a "|,
System.out.println{"good Hobbit name"|,
}
}
}
class TestArrays {
public static void main{String args| {
int index = new int4,
index0 = l,
indexl = 3,
index2 = 0,
index3 = 2,
String islands = new String4,
islands0 = "Bermuda",
islandsl = "Fii",
islands2 = "Azores",
islands3 = "Cozumel",
int y = 0,
int ref,
while {y < 4| {
ref = indexy,
System.out.print{"island = "|,
System.out.println{islandsref|,
y = y + l,
}
}
}
File Edit Window Help Bikini
% java TestArrays
island = Fiji
island = Cozumel
island = Bermuda
island = Azores
exercise soIutions
[yej, ]a(jn,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
primitives and references
69
class Triangle {
double area,
int height,
int length,
public static void main{String args| {
int = 0;
TriungIe [ j tu = new TriungIe[4j;
while { - 4 | {
tu[j = new TriungIe{};
tu[j.height = {x + l| * 2,
tu[j.length = x + 4,
tu[j,setAreu{};
System.out.print{"triangle "+x+", area"|,
System.out.println{" = " + tu[j.area|,
= + 1;
}
int y = ;
x = 27,
Triangle t5 = ta2,
ta2.area = 343,
System.out.print{"y = " + y|,
System.out.println{", t5 area = "+ t5.area|,
}
void setArea{| {
ureu = {height * length| / 2,
}
}
class Triangle {
double area,
int height,
int length,
public static void main{String args| {
int = 0;
TriungIe [ j tu = new TriungIe[4j;
while { - 4 | { 4
tu[j = new TriungIe{};
tu[j.height = {x + l| * 2,
tu[j.length = x + 4,
tu[j,setAreu{};
System.out.print{"triangle "+x+", area"|,
System.out.println{" = " + tu[j.area|,
= + 1;
}
int y = ;
x = 27,
Triangle t5 = ta2,
ta2.area = 343,
System.out.print{"y = " + y|,
System.out.println{", t5 area = "+ t5.area|,
}
void setArea{| {
ureu = {height * length| / 2,
}
} File Edit Window Help Bermuda
%java Triangle
triangle 0, area = 4.0
triangle 1, area = 10.0
triangle 2, area = 18.0
triangle 3, area = Z,0
y = 4 t ureu = 343
Reference VariabIes: Heapuiz Dbjects:
Thc casc of thc piIfcrcd rcfcrcnccs
Tawny coulu scc ihai Kcni`s mcihou hau a sciious
uaw. Ii`s iiuc ihai hc uiun`i usc as many iclcicncc
vaiiallcs as Bol, lui ihcic was no way io acccss any
lui ihc lasi ol ihc Coniaci ol|ccis ihai his mcihou cic-
aicu. Wiih cach iii ihiough ihc loo, hc was assign-
ing a ncw ol|cci io ihc onc iclcicncc vaiiallc, so ihc
icviously iclcicnccu ol|cci was alanuoncu on ihc
hca - ur.enLnbIe. Wiihoui acccss io ninc ol ihc icn
ol|ccis cicaicu, Kcni`s mcihou was usclcss.
(T|e sollWare Was a |ue success ard l|e c||erl ave TaWry ard 8oo ar exlra Wee|
|r laWa||. we'd |||e lo le|| you l|al oy l|r|s||r l||s ooo| you loo W||| el slull |||e l|al.)
hq[0]
hq[I]
hq[Z]
hq[3]
hq[4]
]azz] ]a(jn,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
4 methods use instance variabIes
this is a new chapter 71
State affects behavior, behavior affects state. we know that ob|ects
have state and behavior, represented by instance variabIes and methods. 8ut until now, we
haven't looked at how state and behavior are teloteJ. we already know that each instance of a
class (each ob|ect of a particular type) can have its own unique values for its instance variables.
Dog A can have a nome "Pido and a we|ht of 70 pounds. Dog 8 is "Killer and weighs 9 pounds.
And if the Dog class has a method makeNoise(), well, don't you think a 70-pound dog barks a
bit deeper than the little 9-pounderI (Assuming that annoying yippy sound can be considered
a ootl.) Portunately, that's the whole point of an ob|ectit has oehov|ot that acts on its stote. |n
other words, merheJs use insrnnce vnrinble vnlues. Like, "if dog is less than l4 pounds, make
yippy sound, else... or "increase weight by 5. Lers ge chnnge seme srnre.
How Ob]ects Behave
This oughfo
chonge her sfofel
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
72 chapter 4
objects have state and behavior
A class is thc blucprint Ior an objcct. Whcn you
wiiic a class, you`ic ucsciiling how ihc ]VM
shoulu maIc an ol|cci ol ihai iyc. You alicauy
Inow ihai cvciy ol|cci ol ihai iyc can havc
uillcicni .rnre .n..nbIe valucs. Bui whai aloui
ihc mcihous.
0zn cvcry e|jcr! ef !hz! !ypc hzvc 4|ffcrcn!
mc!he4 |chzv|er!
Wcll... *
Evciy insiancc ol a aiiiculai class has ihc samc
mcihous, lui ihc mcihous can beLn.e uillcicnily
lascu on ihc valuc ol ihc insiancc vaiiallcs.
Thc Song class has iwo insiancc vaiiallcs, .Ie
anu n... Thc lay) mcihou lays a song, lui
ihc insiancc you call lay) on will lay ihc song
icicscnicu ly ihc valuc ol ihc .Ie insiancc
vaiiallc loi ihai insiancc. So, il you call ihc lay)
mcihou on onc insiancc you`ll hcai ihc song
PoliiiI", whilc anoihci insiancc lays DaiIsiai".
Thc mcihou couc, howcvci, is ihc samc.
void play() {
soundPlayer.playSound(title);
}
t|t|e
art|st
setT|t|e(}
setArt|st(}
p|ay(}
| ns!znrc
vzr| z||cs
(state}
mc!he4s
(behav|or}
knews
4ecs
*Yes, another stunningly clear answer!
Kcmcm|cr: z r|zss 4csrr||cs whz! zn
e|jcr! knews zn4 whz! zn e|jcr! 4ecs
PoIitik
CoIdpIoy
Sing
Trovis
Durkstur
0rofefuI
Deod
My Wuy
Sinofro
My Wuy
Sex PisfoIs
Song
t2.play();
Song
s3.play();
c
.
||-
|.
]
|` -
- l
: -:l
.
-:-
-
|| :.
-:-
-' l
-
|.
]
c.||- |.]|` -- l: -:l.-:-
-|| :.-:- M] w.]' l- |.]
|-l --l l- -.l-. ---`
Song t2 = new Song();
t2.setArtist(Travis);
t2.setTitle(Sing);
Song s3 = new Song();
s3.setArtist(Sex Pistols);
s3.setTitle(My Way);
-
-
:
l
.
-
:
-
:
-
:
|.
:
:
-
-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
methods use instance variabIes
73
Ihc s|zc zffcr!s !hc |zrk
A small Dog`s laiI is uillcicni liom a lig Dog`s laiI.
Thc Dog class has an insiancc vaiiallc ..e, ihai ihc
bn.I() mcihou uscs io ucciuc whai Iinu ol laiI sounu
io maIc.
s|ze
rare
oar|()
class Dog {
int size;
String name;
void bark() {
if (size > 60) {
System.out.println(Wooof! Wooof!);
} else if (size > 14) {
System.out.println(Ruff! Ruff!);
} else {
System.out.println(Yip! Yip!);
}
}
}
class DogTestDrive {
public static void main (String[] args) {
Dog one = new Dog();
one.size = 70;
Dog two = new Dog();
two.size = 8;
Dog three = new Dog();
three.size = 35;
one.bark();
two.bark();
three.bark();
}
}
File Edit Window Help Playdead
%java DogTestDrive
Wooof! Wooof!
Yip! Yip!
Ruff! Ruff!
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
74 chapter 4
0
0
0
0
0
0
I
I
inf
method parameters
Yee rzn scn4 !h|n]s !e z mc!he4
]usi as you cxcci liom any iogiamming languagc, you can ass valucs inio
youi mcihous. You mighi, loi cxamlc, wani io icll a Dog ol|cci how many
iimcs io laiI ly calling:
d.bark(3);
Dccnuing on youi iogiamming lacIgiounu anu cisonal iclcicnccs,
,ou mighi usc ihc icim n.uer oi cihas n.nee. loi ihc valucs asscu
inio a mcihou. Alihough ihcic n.e loimal comuici scicncc uisiinciions ihai
colc who wcai lal coais anu who will almosi cciiainly noi icau ihis looI,
maIc, wc havc liggci hsh io liy in ihis looI. So ,ou can call ihcm whaicvci
you liIc aigumcnis, uonuis, haiilalls, cic.) lui wc`ic uoing ii liIc ihis:
A method uses parameters. A caIIer passes arguments.
Aigumcnis aic ihc ihings you ass inio ihc mcihous. An orgument a valuc
liIc 2, Ioo", oi a iclcicncc io a Dog) lanus lacc-uown inio a... waii loi ii...
porometer. Anu a aiamcici is noihing moic ihan a local vaiiallc. A vaiiallc
wiih a iyc anu a namc, ihai can lc uscu insiuc ihc louy ol ihc mcihou.
Bui hcic`s ihc imoiiani aii: II a mcthod takcs a paramctcr, you must pass
it somcthing. Anu ihai somcihing musi lc a valuc ol ihc aioiiaic iyc.
void bark(int numOfBarks) {
while (numOfBarks > 0) {
System.out.println(ruff);
numOfBarks = numOfBarks - 1;
}
}
Dog d = new Dog();
d.bark(3);
-
:-
l
]
-
:
-
-
:l
-
.
l
:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
76 chapter 4
muItipIe arguments
1- .-----l: ]-- .:: |.- - l- :.--
---- ]-- .::- l-- |-:l .-----l |.-:
- l- -:l .-.--l--, :-:-- .-----l -
l- :-:-- .-.--l--, .- :- --
Yee rzn scn4 merc !hzn enc !h|n]
!e z mc!he4
Mcihous can havc muliilc aiamcicis. Scaiaic ihcm
wiih commas whcn you ucclaic ihcm, anu scaiaic ihc
aigumcnis wiih commas whcn you ass ihcm. Mosi
imoiianily, il a mcihou has aiamcicis, you ass
aigumcnis ol ihc iighi iyc anu oiuci.
void takeTwo(int x, int y) {
int z = x + y;
System.out.println(Total is + z);
}
void go() {
TestStuff t = new TestStuff();
t.takeTwo(12, 34);
}
0z| || n] z ! we-pzrzmc!cr mc!he4, zn4 scn4| n]
| ! ! we zr]emcn!s.
void takeTwo(int x, int y) {
int z = x + y;
System.out.println(Total is + z);
}
void go() {
int foo = 7;
int bar = 3;
t.takeTwo(foo, bar);
}
Yee rzn pzss vzr| z||cs | n!e z mc!he4, zs |en] zs
!hc vzr| z||c ! ypc mz!rhcs !hc pzrzmc!cr ! ypc.
1
- .
|--: -
-
-
.
-
.
- |.
-
-
l
.
-
]
.
-.
-
-l
--:
-
-
-
-
l
-
l
: -
.
--
--
l
:.
| l
-
l
-
l
: -
-
-
|l
l
.
l
l
---
-
- l
- -
l
--- '7
'` .
-
l
: -
]
.
--
--
l
:.
| l
-
l
-
l
: -
.
-
w.l': l- .|-- - - |l': l- :.--
--:-|l ]--' -l ]-- .- -- +
.- .l l- l-- ]-- .::- l-- -l-
l- l.-1-- --l-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
methods use instance variabIes
77
1zvz |s pzss-|y-vz|ec.
Ihz! mczns pzss-|y-repy.
int x = 7;
0
0
0
0
0
I
I
I
inf
X
DecIore on inf voriobIe ond ossign if
fhe voIue '7'. The bif poffern for 7
goes info fhe voriobIe nomed x.
void go(int z){ }
DecIore o mefhod wifh on inf
poromefer nomed ;.
inf
Z
0
0
0
0
0
I
I
I
inf
X
-
l
-
-
:l
.
-
:
-
.
-
.
|-
-
.
l
-
M
.- l- -ll-- .-
:-ll-- -
-l-: -|:
!-- l-- l- --l-: --'l --.||]
. --- --:l--.|l], l- :--| l-
: l.l ]-- :.- :.-- ]--- --
|.l-- ]-- :.- :--- .: .- -.- .
--l- :.--, .:l--, -ll--
s|ze
el3|ze( )
sel3|ze( )
oar|( )
Any place where a
particular value can
be used, a method
call that returns that
type can be used.
insteud of:
inf x ~ 3 + Z4,
you cun suy:
inf x ~ 3 + one.gefSi;e(),
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
methods use instance variabIes
83
Hew 4e e|jcr!s |n zn zrrzy
|chzvc!
Dog orroy objecf (Dog[])
Dog[]
pets[0].setSize(30);
int x = pets[0].getSize();
pets[1].setSize(8);
CoII mefhods on fhe fwo Dog
objecfs.
30
si;e
8
si;e
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
84 chapter 4
You alicauy Inow ihai a vaiiallc ucclaiaiion nccus ai lcasi a namc
anu a iyc:
int size;
String name;
Anu you Inow ihai you can iniiializc assign a valuc) io ihc
vaiiallc ai ihc samc iimc:
int size = 420;
String name = Donny;
Bui whcn you uon`i iniiializc an insiancc vaiiallc, whai hacns
whcn you call a gciici mcihou. In oihci woius, whai is ihc .nIue ol
an insiancc vaiiallc beo.e you iniiializc ii.
Pcr|zr|n] zn4 |n| !|z||z|n]
|ns!znrc vzr|z||cs
class PoorDog {
private int size;
private String name;
public int getSize() {
return size;
}
public String getName() {
return name;
}
}
public class PoorDogTestDrive {
public static void main (String[] args) {
PoorDog one = new PoorDog();
System.out.println(Dog size is + one.getSize());
System.out.println(Dog name is + one.getName());
}
}
nstance variables
always get a
default value. f
you don't explicitly
assign a value
to an instance
variable, or you
don't call a setter
method, the
instance variable
still has a valuel
|ntegers 0
f|oat|ng po|nts 0.0
boo|eans fa|se
references nu||
-:|.-- l-- -:l.-:- .-.|-:,
-l --'l .::- . .|--
w.l -|| l-:- --l---
w
.l
- ]-- l
- w
||
l
: --- :--
|-
File Edit Window Help CallVet
% java PoorDogTestDrive
Dog size is 0
Dog name is null
/-- --'l .- l- -l.|-- -:l.-:- .-.|-:,
-:.-:- l-] .|-.]: .- . -.-|l .|-- N----
--l-: |-:|-- :.-` -l o, --|-.-: -l .|:-,
.- --:l ------:- .-.|-: -l --||
|------, --|| -:l --.-: . ----l- :--l--| l.l
:-'l :--l--||- / ---.--- l- .-]l- A
------:-, -l -- .:l-.| --:l
initiaIizing instance variabIes
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
methods use instance variabIes
85
Ihc 4|ffcrcnrc |c! wccn |ns!znrc
zn4 |erz| vzr|z||cs
Instunce voriobIes ore decIored
inside o cIoss buf nof wifhin o mefhod.
class Horse {
private double height = 15.2;
private String breed;
// more code...
}
LocuI voriobIes ore decIored wifhin o mefhod.
class AddThing {
int a;
int b = 12;
public int add() {
int total = a + b;
return total;
}
}
Local variables do
NOT get a default
valuel The compiler
complains if you
try to use a local
variable before
the variable is
initialized.
LocuI voriobIes MUST be inifioIi;ed before usel
class Foo {
public void go() {
int x;
int z = x + 3;
}
}
w--'l :--|-'' /-- :.-
-:|.-- -l--l . .|--,
-l .: :--- .: ]-- l-]
l- c! l, l- :--|--
--.: --l
File Edit Window Help Yikes
% javac Foo.java
Foo.java:4: variable x might
not have been initialized
int z = x + 3;
1 error ^
(-,- a,- |
oa|| qa--(:|-
Foo
Foo
. == : : l---
. == : .|:-
l- l .ll---: .-- l-
:.-
- -- . .- :, :- l-]
.-- --.| -:- =
=
Use == to compare
two primitives,
or to see if two
references refer to
the same ob]ect.
Use the equals{}
method to see
if two different
ob]ects are equal.
{8uch as two different
8tring ob]ects that both
represent the characters
in Fred}
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
methods use instance variabIes
87
+,-+ :+ ,-+:.|
What's IegaI?
0iven fhe mefhod beIow, which
of fhe mefhod coIIs Iisfed on fhe
righf ore IegoI7
Puf o checkmork nexf fo fhe
ones fhof ore IegoI. (Some
sfofemenfs ore fhere fo ossign
voIues used in fhe mefhod coIIs).
int calcArea(int height, int width) {
return height * width;
}
int a = calcArea(7, 12);
short c = 7;
calcArea(c,15);
int d = calcArea(57);
calcArea(2,3);
long t = 42;
int f = calcArea(t,17);
int g = calcArea();
calcArea();
byte h = calcArea(4,20);
int j = calcArea(2,3,5);
I oIwoys
keep my voriobIes
privofe. If you wonf fo
see fhem, you hove fo
foIk fo my mefhods.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
90 chapter 4
A short 1ava program is listed to your right.
Two blocks of the program are missing.
our challenge is to match the candidate
bIocks of code (below), with the output
that you'd see if the blocks were inserted.
Not all the lines of output will be used, and
some of the lines of output might be used
more than once. Draw lines connecting
the candidate blocks of code with their
matching command-line output.
x < 9
index < 5
x < 20
index < 5
x < 7
index < 7
x < l9
index < l
l4 7
9 5
l9 l
l4 l
25 l
7 7
20 l
20 5
Candidates: PossibIe output:
public class Mix4 {
int counter = 0;
public static void main(String [] args) {
int count = 0;
Mix4 [] m4a =new Mix4[20];
int x = 0;
while ( ) {
m4a[x] = new Mix4();
m4a[x].counter = m4a[x].counter + 1;
count = count + 1;
count = count + m4a[x].maybeNew(x);
x = x + 1;
}
System.out.println(count +
+ m4a[1].counter);
}
public int maybeNew(int index) {
if ( ) {
Mix4 m4 = new Mix4();
m4.counter = m4.counter + 1;
return 1;
}
return 0;
}
}
puzzIe: Mixed Messages
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
methods use instance variabIes
91
ivar
factor
public
private
our is to take code snippets from the
pool and place them into the blank lines
in the code. ou may not use the same
snippet more than once, and you won't
need to use all the snippets. our
is to make a class that will compile and
run and produce the output listed.
public class Puzzle4 {
public static void main{String args| {
___________________________________
int y = l,
int x = 0,
int result = 0,
while {x < 6| {
___________________________
___________________________
y = y * l0,
_________________
}
x = 6,
while {x > 0| {
_________________
result = result + ___________________
}
System.out.println{"result " + result|,
}
}
class ___________ {
int ivar,
________ ______ doStuff{int _________| {
if {ivar > l00| {
return _________________________
} else {
return _________________________
}
}
}
Note: ach snippet
from the pooI can be
used onIy oncel
File Edit Window Help BellyFlop
%java Puzzle4
result 543345
Dutput
Puzzle4 | | obs new Puzzle4|6|,
Puzzle4b | | obs new Puzzle4b|6|,
Puzzle4b | | obs new Puzzle4|6|,
obs |x| new Puzzle4b(x),
obs | | new Puzzle4b( ),
obs |x| new Puzzle4b( ),
obs new Puzzle4b( ),
doStuff(x),
obs.doStuff(x),
obs|x|.doStuff(factor),
obs|x|.doStuff(x),
ivar x,
obs.ivar x,
obs|x|.ivar x,
obs|x|.ivar y,
ivar + factor,
ivar ` (2 + factor),
ivar ` (5 - factor),
ivar ` factor,
x x + l,
x x - l,
Puzzle4
Puzzle4b
Puzzle4b( )
int
short
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
92 chapter 4
Fast Times in Stim-City
When Buchanan jammed his twitch-gun into Jai`s side, Jai Iroze. Jai knew that Buchanan
was as stupid as he was ugly and he didn`t want to spook the big guy. Buchanan ordered Jai
into his boss`s oIfce, but Jai`d done nothing wrong, (lately), so he fgured a little chat with
Buchanan`s boss Leveler couldn`t be too bad. He`d been moving lots oI neural-stimmers in
the west side lately and he fgured Leveler would be pleased. Black market stimmers weren`t
the best money pump around, but they were pretty harmless. Most oI the stim-junkies he`d
seen tapped out aIter a while and got back to liIe, maybe just a little less Iocused than beIore.
Leveler`s oIfce` was a skungy looking skimmer, but once Buchanan shoved him in, Jai
could see that it`d been modifed to provide all the extra speed and armor that a local boss like
Leveler could hope Ior. 'Jai my boy, hissed Leveler, 'pleasure to see you again. 'Likewise
I`m sure..., said Jai, sensing the malice behind Leveler`s greeting, 'We should be square
Leveler, have I missed something? 'Ha! You`re making it look pretty good Jai, your volume
is up, but I`ve been experiencing, shall we say, a little breach` lately... said Leveler.
Jai winced involuntarily, he`d been a top drawer jack-hacker in his day. Anytime someone
fgured out how to break a street-jack`s security, unwanted attention turned toward Jai. 'No
way it`s me man, said Jai, 'not worth the downside. I`m retired Irom hacking, I just move
my stuII and mind my own business. 'Yeah, yeah, laughed Leveler, 'I`m sure you`re
clean on this one, but I`ll be losing big margins until this new jack-hacker is shut
out! 'Well, best oI luck Leveler, maybe you could just drop me here and I`ll go
move a Iew more units` Ior you beIore I wrap up today, said Jai.
'I`m aIraid it`s not that easy Jai, Buchanan here tells me that word is you`re
current on J37NE, insinuated Leveler. 'Neural Edition? sure I play around a bit, so
what?, Jai responded Ieeling a little queasy. 'Neural edition`s how I let the stim-junkies
know where the next drop will be, explained Leveler. 'Trouble is, some stim-junkie`s stayed
straight long enough to fgure out how to hack into my WareHousing database. 'I need a
quick thinker like yourselI Jai, to take a look at my StimDrop J37NE class; methods, instance
variables, the whole enchilada, and fgure out how they`re getting in. It should.., 'HEY!,
exclaimed Buchanan, 'I don`t want no scum hacker like Jai nosin` around my code! 'Easy
big guy, Jai saw his chance, 'I`m sure you did a top rate job with your access modi.. 'Don`t
tell me - bit twiddler!, shouted Buchanan, 'I leIt all oI those junkie level methods public,
so they could access the drop site data, but I marked all the critical WareHousing methods
private. Nobody on the outside can access those methods buddy, nobody!
'I think I can spot your leak Leveler, what say we drop Buchanan here oII at the corner
and take a cruise around the block, suggested Jai. Buchanan reached Ior his twitch-gun but
Leveler`s stunner was already on Buchanan`s neck, 'Let it go Buchanan, sneered Leveler,
'Drop the twitcher and step outside, I think Jai and I have some plans to make.
What did 1ai suspect?
Will he get out of Leveler`s skimmer with all his bones intact?
]Jc_Jna[c
_s[ci
puzzIe: Five Minute Mystery
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
methods use instance variabIes
93
A class can have any number of these.
A method can have only one of these.
This can be implicitly promoted.
prefer my instance variables private.
t really means 'make a copy'.
Only setters should update these.
A method can have many of these.
return something by defnition.
shouldn't be used with instance variables
can have many arguments.
By defnition, take one argument.
These help create encapsulation.
always fy solo.
instunce vuriubIes getter settermethod
return
return urgument
encupsuIution
puss by vuIue
instunce vuriubIes
urgument
getter
pubIic
method
setter
getter setter pubIic privute
return
A Class 'XCopy' compiles and runs as it stands ! The
output is: '42 84'. Remember Java is pass by value, (which
means pass by copy), the variable 'orig' is not changed by the
go( ) method.
class Clock {
String time,
void setTime{String t| {
time = t,
}
String getTime{| {
return time,
}
}
class ClockTestDrive {
public static void main{String args| {
Clock c = new Clock{|,
c.setTime{"l245"|,
String tod = c.getTime{|,
System.out.println{"time: " + tod|,
}
} Mofe: '0effer' mefhods hove o refurn
fype by defnifion.
[yej, ]a(jn,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
94 chapter 4
public class Puzzle4 {
public static void main{String args| {
Pu;;Ie4b [ ] obs ~ new Pu;;Ie4b[o],
int y = l,
int x = 0,
int result = 0,
while {x < 6| {
obs[x] ~ new Pu;;Ie4b( ),
obs[x] . ivor ~ y,
y = y * l0,
x ~ x + I,
}
x = 6,
while {x > 0| {
x ~ x - I,
result = result + obs[x].doSfuff(x),
}
System.out.println{"result " + result|,
}
}
class Pu;;Ie4b {
int ivar,
pubIic inf doStuff{int focfor| {
if {ivar > l00| {
return ivor * focfor,
} else {
return ivor * (b - focfor),
}
}
}
File Edit Window Help BellyFlop
%java Puzzle4
result 543345
Dutput
x < 9
index < 5
x < 20
index < 5
x < 7
index < 7
x < l9
index < l
l4 7
9 5
l9 l
l4 l
25 l
7 7
20 l
20 5
Candidates: PossibIe output:
Answer to the 5-minute mystery...
Jai knew that Buchanan wasn`t the sharpest
pencil in the box. When Jai heard Buchanan
talk about his code, Buchanan never mentioned
his instance variables. Jai suspected that
while Buchanan did in Iact handle his methods
correctly, he Iailed to mark his instance variables
private. That slip up could have easily cost
Leveler thousands.
puzzIe answers
]azz] ]a(jn,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
5 writing a program
this is a new chapter 95
Let's put some muscIe in our methods. we dabbled with variables, played
with a few ob|ects, and wrote a little code. 8ut we were weak. we need more tools. Like
operators. we need more operators so we can do something a little more interesting than, say,
ootl. And Ioops. we need loops, but what's with the wimpy wh|le loopsI we need loops
if we're really serious. Might be useful to generate random numbers. And turn a String
into an int, yeah, that would be cool. 8etter learn that too. And why don't we learn it all by
ou|lJ|n something real, to see what it's like to write (and test) a program from scratch. Maybe
a game, like 8attleships. That's a heavy-lifting task, so it'll take two chapters to finish. we'll build
a simple version in this chapter, and then build a more powerful deluxe version in chapter 6.
Extra-8trength Methods
I con Iiff
heovy objecfs.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
96 chapter 5
Ic!s |e||4 z Bz!!|csh|p-s!y|c
]zmc: 8|nk z Pe! 0em
Ii`s you againsi ihc comuici, lui unliIc ihc ical
Baiilcshi gamc, in ihis onc you uon`i lacc any shis
ol youi own. Insicau, youi |ol is io sinI ihc comuici`s
shis in ihc lcwcsi numlci ol gucsscs.
Oh, anu wc aicn`i sinIing shis. Wc`ic Iilling Doi
Coms. Thus csiallishing lusincss iclcvancy so you can
cxcnsc ihc cosi ol ihis looI).
Goal: SinI all ol ihc comuici`s Doi Coms in ihc lcwcsi
numlci ol gucsscs. You`ic givcn a iaiing oi lcvcl, lascu
on how wcll you ciloim.
Sctup: Whcn ihc gamc iogiam is launchcu, ihc
comuici laccs ihicc Doi Coms on a virtual 7 x 7
grid. Whcn ihai`s comlcic, ihc gamc asIs loi youi hisi
gucss.
How you play: Wc havcn`i lcaincu io luilu a GUI yci, so
ihis vcision woiIs ai ihc commanu-linc. Thc comuici
will iomi you io cnici a gucss a ccll), ihai you`ll iyc
ai ihc commanu-linc as AS", C", cic.). In icsonsc
io youi gucss, you`ll scc a icsuli ai ihc commanu-
linc, ciihci Hii", Miss", oi You sunI Pcis.com" oi
whaicvci ihc lucIy Doi Com ol ihc uay is). Whcn
you`vc scni all ihicc Doi Coms io ihai lig 404 in ihc
sIy, ihc gamc cnus ly iiniing oui youi iaiing.
7 x 7 -
File Edit Window Help Sell
%java DotComBust
Enter a guess A3
miss
Enter a guess B2
miss
Enter a guess C4
miss
Enter a guess D2
hit
Enter a guess D3
hit
Enter a guess D4
Ouch! You sunk Pets.com : (
kill
Enter a guess B4
miss
Enter a guess G3
hit
Enter a guess G4
hit
Enter a guess G5
Ouch! You sunk AskMe.com : (
kill
Enter a guess A7
miss
Enter a guess B7
A
C
D
F
C
0 1 2 3 4 5 6
AskMe.com
Pets.com
C
o
2
.
c
o
m
:l.-l: .l ----, |- ).. .--.]:
pzr! ef z ]zmc |n!crzr!|en
You're going to build the
Sink a Dot Com game, with
a 7 x 7 grid and three
Dot Coms. Each Dot Com
takes up three cells.
-.: -
: . :-||'
buiIding a reaI game
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
writing a program
97
I|rs!, z h|]h-|cvc| 4cs|]n
Wc Inow wc`ll nccu classcs anu mcihous, lui whai
shoulu ihcy lc. To answci ihai, wc nccu moic
inloimaiion aloui whai ihc gamc shoulu uo.
Iiisi, wc nccu io hguic oui ihc gcncial uow ol ihc
gamc. Hcic`s ihc lasic iuca:
0ome fnishes
0ive fhe user o rofing bosed on
fhe number of guesses.
Sforf
0ome sef-up
0ef user
guess
Check
guess
hif miss
remove Ioco-
fion ceII
kiII
remove
Dof Com
yes
no
sfiII some
Dof Coms
oIive7
dispIoy user
score/rofing
gome
over
Whoa. A real fow chart.
Now wc havc an iuca ol ihc Iinus ol ihings ihc
iogiam nccus io uo. Thc ncxi sic is hguiing
oui whai Iinu ol wc`ll nccu io uo ihc
woiI. Rcmcmlci, ihinI liIc Biau iaihci ihan
Iaiiy, locus hisi on ihc things in ihc iogiam
iaihci ihan ihc procedures.
A
:-:|- --.-:
:l.-l -- -:
A
--:l.-|- :
-:- l- ----:--l
.- .:l--
A .---
----:--l: .
-::-- --l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
98 chapter 5
8|mp|e0ot6omCame
vo|d ra|r
8|mp|e0ot6om
|rl [| |ocal|orCe||s
|rl rur0ll|ls
3lr|r c|ec|Yourse|l(3lr|r uess)
vo|d selLocal|orCe||s(|rl[| |oc)
remp|c!c ]zmc |n!crzr!|en
Ihc 8|mp|c Pe! 0em 0zmc
z ]cn!|cr |n!re4er!|en
Ii looIs liIc wc`ic gonna nccu ai lcasi iwo classcs, a
Gamc class anu a DoiCom class. Bui lcloic wc luilu
ihc lull moniy Sinh o Dot Com gamc, wc`ll siaii wiih
a siiicu-uown, simlih cu vcision, SimpIe Dot Com
Come. Wc`ll luilu ihc simlc vcision in L. chaici,
lollowcu ly ihc ucluxc vcision ihai wc luilu in ihc
re: chaici.
Evciyihing is simlci in ihis gamc. Insicau ol a 2-D
giiu, wc hiuc ihc Doi Com in |usi a singlc .ow. Anu
insicau ol L.ee Doi Coms, wc usc ore.
Thc goal is ihc samc, ihough, so ihc gamc siill nccus
io maIc a DoiCom insiancc, assign ii a locaiion
somcwhcic in ihc iow, gci usci inui, anu whcn all
ol ihc DoiCom`s cclls havc lccn hii, ihc gamc is ovci.
This simlih cu vcision ol ihc
gamc givcs us a lig hcau siaii
on luiluing ihc lull gamc.
Il wc can gci ihis small onc
woiIing, wc can scalc ii u io
ihc moic comlcx onc laici.
In ihis simlc vcision, ihc
gamc class has no insiancc
vaiiallcs, anu all ihc gamc
couc is in ihc main) mcihou.
In oihci woius, whcn ihc
iogiam is launchcu anu
main) lcgins io iun, ii will
maIc ihc onc anu only DoiCom
insiancc, icI a locaiion loi ii ihicc
consccuiivc cclls on ihc singlc viiiual
scvcn-ccll iow), asI ihc usci loi a gucss, chccI ihc
gucss, anu iccai uniil all ihicc cclls havc lccn hii.
Kcc in minu ihai ihc viiiual iow is... ...unI. In oihci
woius, ii uocsn`i cxisi anywhcic in ihc iogiam. As
long as loih ihc gamc anu ihc usci Inow ihai ihc
DoiCom is hiuucn in ihicc consccuiivc cclls oui ol a
ossillc scvcn siaiiing ai zcio), ihc iow iiscll uocsn`i
havc io lc icicscnicu in couc. You mighi lc icmicu
io luilu an aiiay ol scvcn inis anu ihcn assign ihc
DoiCom io ihicc ol ihc scvcn clcmcnis in ihc aiiay,
lui you uon`i nccu io. All wc nccu is an aiiay ihai
holus |usi ihc ihicc cclls ihc DoiCom occuics.
8impleDotCom class
write prep code
write test code
write f nal Java code
8impleDotComGame
class
write prep code
write test code [no]
write f nal Java code
prep code test code reaI code
This bar is displayed on the next set of pages to tell
you which part you're working on. Por example, if you
see this picture at the top of a page, it means you're
working on prepcode for the SimpleDotCom class.
prep code test code reaI code
3|rp|e0olCor c|ass
prep code
FIex those dendrites.
How wouId you decide which cIass or cIasses
to buiId , when you're writing a program!
Assuming that aII but the tiniest programs
need more than one cIass (if you're foIIowing
good DD principIes and not having cIass
do many different jobs), where do you start!
WWkm
Qw&W
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
100 chapter 5
8|mp|e0ot6om
|rl [| |ocal|orCe||s
|rl rur0ll|ls
3lr|r c|ec|Yourse|l(3lr|r uess)
vo|d selLocal|orCe||s(|rl[| |oc)
You`ll gci ihc iuca ol how iccouc oui vcision ol scuuocouc) woiIs as you
icau ihiough ihis cxamlc. Ii`s soii ol hall-way lciwccn ical ]ava couc anu a lain
English ucsciiiion ol ihc class. Mosi iccouc incluucs ihicc aiis: insiancc
vaiiallc ucclaiaiions, mcihou ucclaiaiions, mcihou logic. Thc mosi imoiiani
aii ol iccouc is ihc mcihou logic, lccausc ii uch ncs has io hacn,
which wc laici iianslaic inio , whcn wc aciually wiiic ihc mcihou couc.
prep code test code reaI code prep code
DECLARE ao |nt orro, to |o|o t|o |ocat|oo co||s. Ca|| |t |ocot|onCe||s.
DECLARE ao |nt to |o|o t|o oobo o ||ts. Ca|| |t num0fH|ts aoo 5EY |t to 0.
DECLARE a checkourse|f(j ot|oo t|at ta'os a Str|ng o t|o oso's gooss ('+', '3', otc.),
c|oc's |t, aoo otoos a oso|t oposoot|og a '||t', '|ss', o ''|||'.
DECLARE a setLocot|onCe||s(j sotto ot|oo t|at ta'os ao |nt orro, (.||c| |as t|o t|oo co||
|ocat|oos as |nts (2,3,+, otc.).
MEYHOD. Str|ng checkourse|f(Str|ng userCuessj
GEY t|o oso gooss as a St|og paaoto
CONVERY t|o oso gooss to ao |nt
REPEAY .|t| oac| o t|o |ocat|oo co||s |o t|o |nt aa
// COmPAR t|o oso gooss to t|o |ocat|oo co||
IF t|o oso gooss atc|os
INCREMENY t|o oobo o ||ts
// lIND OUT | |t .as t|o |ast |ocat|oo co||.
IF oobo o ||ts |s 3, REYURN ''|||' as t|o oso|t
EL5E |t .as oot a '|||, so REYURN'||t'
||| ||
EL5E t|o oso gooss o|o oot atc|, so REYURN '|ss'
||| ||
||| ||||/T
||| ||TC|
MEYHOD. vo|d setLocot|onCe||s(|nt[] ce||Locot|onsj
GEY t|o co|| |ocat|oos as ao |nt orro, paaoto
A55IGN t|o co|| |ocat|oos paaoto to t|o co|| |ocat|oos |ostaoco va|ab|o
||| ||TC|
SimpIeDotCom cIass
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
writing a program
101
Wr| !| n] !hc mc!he4
|mp|cmcn!z!|ens
|c!s wr| !c !hc rcz|
mc!he4 re4c new, zn4 ]c!
!h|s peppy werk|n].
Bcloic wc siaii couing ihc
mcihous, ihough, lci`s lacI
u anu wiiic somc couc io
e ihc mcihous. Thai`s iighi,
wc`ic wiiiing ihc icsi couc
beo.e ihcic`s anyihing io icsi!
Thc concci ol wiiiing
ihc icsi couc hisi is onc ol
ihc iaciiccs ol Exiicmc
Piogiamming XP), anu
ii can maIc ii casici anu
lasici) loi you io wiiic youi
couc. Wc`ic noi ncccssaiily
saying you shoulu usc XP,
lui wc uo liIc ihc aii aloui
wiiiing icsis hisi. Anu XP |usi
ourJ cool.
Oh myl For o minufe
fhere I fhoughf you
weren'f gonno wrife your
fesf code frsf. Whool
Don'f score me Iike fhof.
Lxtreme Programming(XP) is a newcomer to the software
development methodology world. Considered by many
to be "the way programmers really want to work, XP
emerged in the late 90's and has been adopted by
companies ranging from the two-person garage shop
to the Pord Motor Company. The thrust of XP is that the
customer gets what he wants, when he wants it, even
when the spec changes late in the game.
XP is based on a set of proven practices that are all
designed to work together, although many folks do pick
and choose, and adopt only a portion of XP's rules. These
practices include things like:
Make small, but frequent, releases.
Develop in iteration cycles.
Don't put in anything that's not in the spec (no matter
how tempted you are to put in functionality "for the
future).
write the test code .
No killer schedules, work regular hours.
Pefactor (improve the code) whenever and wherever you
notice the opportunity.
Don't release anything until it passes all the tests.
Set realistic schedules, based around small releases.
Keep it simple.
Program in pairs, and move people around so that
everybody knows pretty much everything about the code.
Extreme Programming (XP)
prep code test code reaI code test code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
102 chapter 5
Wr| !|n] !cs! re4c fer !hc 8|mp|cPe!0em r|zss
MEYHOD Str|ng checkourse|f(Str|ng userCuessj
GEY t|o oso gooss as a St|og paaoto
CONVERY t|o oso gooss to ao |nt
REPEAY .|t| oac| o t|o |ocat|oo co||s |o t|o |nt aa
// COmPAR t|o oso gooss to t|o |ocat|oo co||
IF t|o oso gooss atc|os
INCREMENY t|o oobo o ||ts
// lIND OUT | |t .as t|o |ast |ocat|oo co||.
IF oobo o ||ts |s 3, REYURN '||||' as t|o oso|t
EL5E |t .as oot a '|||, so REYURN'|t'
||| ||
EL5E t|o oso gooss o|o oot atc|, so REYURN '||ss'
||| ||
||| ||||/T
||| ||TC|
Wc nccu io wiiic icsi couc ihai can maIc a SimlcDoiCom ol|cci
anu iun iis mcihous. Ioi ihc SimlcDoiCom class, wc ically
caic aloui only ihc LeIYou.eI() mcihou, alihough wc w.II havc
io imlcmcni ihc e1on.orCeII() mcihou in oiuci io gci ihc
LeIYou.eI() mcihou io iun coiiccily.
TaIc a goou looI ai ihc iccouc lclow loi ihc LeIYou.eI()
mcihou ihc e1on.orCeII() mcihou is a no-liainci sciici mcihou,
so wc`ic noi woiiicu aloui ii, lui in a ical` alicaiion wc mighi
wani a moic iolusi sciici` mcihou, which wc wouIJ wani io icsi).
Thcn asI youiscll, Il ihc chccIYouiscll) mcihou wcic
imlcmcnicu, whai icsi couc coulu I wiiic ihai woulu iovc io mc
ihc mcihou is woiIing coiiccily."
1. nstantiate a SimpleDotCom object.
2. Assign it a location (an array of 3 ints, like
{2,3,4}).
3. Create a String to represent a user guess
(2, 0, etc.).
4. nvoke the checkYourself() method pass-
ing it the fake user guess.
5. Print out the result to see if it's correct
(passed or failed).
Bzsc4 en !h|s prcpre4c: Hcrcs whz! wc shee|4 !cs!:
prep code test code reaI code test code
SimpIeDotCom cIass
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
writing a program
103
public class SimpleDotComTestDrive {
public static void main (String[] args) {
SimpleDotCom dot = new SimpleDotCom();
int[] locations = {2,3,4};
dot.setLocationCells(locations);
String userGuess = 2;
String result = dot.checkYourself(userGuess);
String testResult = failed;
if (result.equals(hit) ) {
testResult = passed;
}
System.out.println(testResult);
}
}
Ics! re4c fer !hc 8|mp|cPe!0em r|zss
(-,- a,- |
oa|| qa--(:|-
-
:
.
l
-
-
What happens in
Integer.parseInt() if the thing you
pass isn't a number! And does it
recognize speIIed-out numbers,
Iike "three"!
CaJe Kagaets
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
120 chapter 5
How does a crossword puzzle
help you learn 1avaI well, all
of the words are 1ava related.
|n addition, the clues provide
metaphors, puns, and the like.
These mental twists and turns
burn alternate routes to 1ava
knowledge, right into your
brain!
Down
2. |ncrement type
3. Class's workhorse
5. Pre is a type of _____
6. Por's iteration ______
7. Lstablish rst value
8. while or Por
9. Update an instance variable
l2. Towards blastoff
l4. A cycle
l6. Talkative package
l9. Method messenger
(abbrev.)
Across
l. Pancy computer word
for build
4. Multi-part loop
6. Test rst
7. 32 bits
l0. Method's answer
ll. Prepcode-esque
l3. Change
l5. The big toolkit
l7. An array unit
l8. |nstance or local
l 2
l2
27
5
25
2l 20
6
29
l7
4
l0
l3
l9
28
26
l8
ll
22
l6
9
7
l4
24 23
3
l5
8
20. Automatic toolkit
22. Looks like a primitive,
but..
25. Un-castable
26. Math method
28. Converter method
29. Leave early
2l. As if
23. Add after
24. Pi house
26. Compile it and ____
27. ++ quantity
puzzIe: JavaCross
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
writing a program
121
class MixFor5 {
public static void main(String [] args) {
int x = 0;
int y = 30;
for (int outer = 0; outer < 3; outer++) {
for(int inner = 4; inner > 1; inner--) {
y = y - 2;
if (x == 6) {
break;
}
x = x + 3;
}
y = y - 2;
}
System.out.println(x + + y);
}
}
A short 1ava program is listed below. One block of the program
is missing. our challenge is to match the candidate bIock of
code (on the left), with the output that you'd see if the block
were inserted. Not all the lines of output will be used, and some
of the lines of output might be used more than once. Draw lines
connecting the candidate blocks of code with their matching
command-line output.
:.-.l- :--
--: ---
-.l: -.:
:.-.l- -l
--- - l-
-::|- --l-l:
x = x + 3,
x = x + 6,
x = x + 2,
x++,
x~~,
x = x + 0,
45 6
36 6
54 6
60 l0
l8 6
6 l4
l2 l4
Candidates: PossibIe output:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
122 chapter 5
class MultiFor {
public static void main{String args| {
for{int x = 0, x < 4, x++| {
for{int y = 4, y > 2, y~~| {
System.out.println{x + " " + y|,
}
if {x == l| { Whut wouId huppen
x++, if this code bIock cume
} before the 'y' for Ioop?
}
}
}
class Output {
public static void main{String args| {
Output o = new Output{|,
o.go{|,
}
void go{| {
int y = 7,
for{int x = l, x < 8, x++| {
y++,
if {x > 4| {
System.out.print{++y + " "|,
}
if {y > l4| {
System.out.println{" x = " + x|,
break,
}
}
}
} Did you remember to fuctor in the
breuk stutement? How did thut
uffect the output?
File Edit Window Help Sleep
% java TestArrays
island = Fiji
island = Cozumel
island = Bermuda
island = Azores
File Edit Window Help MotorcycleMaintenance
% java Output
13 15 x = 6
8e fhe JVM: Code Mognefs:
File Edit Window Help Monopole
% java MultiFor
0 4
0 3
1 4
1 3
3 4
3 3
exercise soIutions
]e;ejze o|ajoz
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
writing a program
123
x = x + 3,
x = x + 6,
x = x + 2,
x++,
x~~,
x = x + 0,
45 6
36 6
54 6
60 l0
l8 6
6 l4
l2 l4
Candidates: PossibIe output:
l 2
l2
27
5
25
2l 20
6
29
l7
4
l0
l3
l9
28
26
l8
ll
22
l6
9
7
l4
24 23
3
l5
8
I M P L E M E M T M
P F O P E
E X T P E M E P I M T
X L S P E T U P M H
P S E U D O C O D E P I O
P E O T C A S T T D
E I C A P I J T I
S T P A O A
S E L E M E M T V A P I A 8 L E
I P M A P I
O A E J A V A . L A M 0 Z
M T M I I E
I M T E 0 E P O P M
O T 8 O O L E A M
P A M D O M U S T
U M P A P S E I M T H
M 8 P E A I L
]azz|e o|ajoz
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
6 get to know the Java API
this is a new chapter 125
Java ships with hundreds of pre-buiIt cIasses. ou don't have to
reinvent the wheel if you know how to find what you need in the 1ava library, known as
the 1ava API. ouve ot oettet th|ns to Jo. |f you're going to write code, you might as well
write only the parts that are truly custom for your application. ou know those programmers
who walk out the door each night at 5 PMI The ones who don't even show u until l0 AMI
7hey use the 1ava API. And about eight pages from now, so will you. The core 1ava library
is a giant pile of classes |ust waiting for you to use like building blocks, to assemble your own
program out of largely pre-built code. The Peady-bake 1ava we use in this book is code you
don't have to create from scratch, but you still have to type it. The 1ava AP| is full of code you
don't even have to tye. All you need to do is learn to use it.
Using the Java Library
I con Iiff
heovy objecfs.
So if's frue7
We don'f hove fo
buiId if ourseIves7
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
126 chapter 6
|n eer |zs! rhzp!cr, wc |cf! yee
w| !h !hc r||ff-hzn]cr. |e].
File Edit Window Help Smile
%java SimpleDotComGame
enter a number 1
miss
enter a number 2
miss
enter a number 3
miss
enter a number 4
hit
enter a number 5
hit
enter a number 6
kill
You took 6 guesses
remp|c!c ]zmc |n!crzr!|en
(your mileage may vary)
Hew | !s seppesc4 !e |eek
Here's whof hoppens when we
run if ond enfer fhe numbers
I,Z,3,4,b,o. Lookin' good.
File Edit Window Help Faint
%java SimpleDotComGame
enter a number 2
hit
enter a number 2
hit
enter a number 2
kill
You took 3 guesses
4|ffcrcn! ]zmc |n!crzr!|en
(yikes)
Here's whof hoppens when we
enfer Z,Z,Z.
Hew !hc |e] |eeks
|n !hc rerrcn! vcrs|en, enrc
yee ]c! z h| !, yee rzn s|mp|y
rcpcz! !hz! h| ! ! we merc
!|mcs fer !hc k||||
we stiII have a bug
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 127
8e whz! hzppcnc4!
public String checkYourself(String stringGuess) {
int guess = Integer.parseInt(stringGuess);
String result = miss;
for (int cell : locationCells) {
if (guess == cell) {
result = hit;
numOfHits++;
break;
} // end if
} // end for
if (numOfHits == locationCells.length) {
result = kill;
} // end if
System.out.println(result);
return result;
} // end method
c----l l- l--
l- .- -l
M.- . .-.|- l- -| l- --:-|l --'||
--l--- |-l -::' - .: l- -.-|l
|- -- .::--- . -::'`
--.l -l -.: l- - l- .--.] c--.-- l- -:--
--:: l- l: -|----l
|:-||`, - l- .--.]
-- -l . l'
6-l --l - l- |--, -- ---
l- l-:l l- -l-- :-||:
w-'-- --l - l- |--, -l
|-l': :-- --'-- --- '-.'
|l ? l--:` .- :.-- l-
--:-|l l-- l- ||'
l:|.] l- --:-|l -- l- -:--
|-::', --|-:: l -.: :.-- l- l' -- ||'`
-l--- l- --:-|l .: l-
l- :.||- --l-
here's where |t
goes wrong. we
counted a h|t every
t|me the user
guessed a ce||
|ocat|on, even if
thet locetion hed
elreedy been hit!
we need a way to
know that when
a user makes
a h|t, he hasn't
prev|ous|y h|t that
ce||. |f he has, then
we don't want to
count |t as a h|t.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
128 chapter 6
A 'l---' - . .-l:-|.- -- - l- .--.] --.-: l.l
l- :-|| |-:.l-- .l l.l :.-- -- - l- 61+!
.--.] ||-:.l--c-||:` .: --- l
Hew 4e wc f| r | ! !
0 1 2 3 4 5 6
We need o woy fo know whefher o ceII hos oIreody been hif. Lef's run
fhrough some possibiIifies, buf frsf, we'II Iook of whof we know so for...
We hove o virfuoI row of 7 ceIIs, ond o DofCom wiII occupy fhree
consecufive ceIIs somewhere in fhof row. This virfuoI row shows o
DofCom pIoced of ceII Iocofions 4,b ond o.
We couId moke o second orroy, ond eoch fime fhe user mokes o hif, we
sfore fhof hif in fhe second orroy, ond fhen check fhof orroy eoch fime
we gef o hif, fo see if fhof ceII hos been hif before.
1- -l-.| ---, -l l-
? :-|| |-:.l--: -- l-
l
-lc-- --:l
The DofCom hos on insfonce voriobIe-on inf orroy-fhof hoIds fhof
DofCom objecf's ceII Iocofions.
0 I Z
4
5
6
1- .--.] -:l.-:- .-.|- l.l
-|: l- l-lc--': :-|| |-:.l--:
1: l-lc-- -|: l- ? .|--: -
+, -, .- | 1-:- .-- l- -----:
l- -:-- ---: l- --::
0p!|en enc
IocutionCeIIs
(insfonce voriobIe of
fhe DofCom)
0 I Z
faIse
hitCeIIs urruy
(fhis wouId be o
new booIeon orroy
insfonce voriobIe of
fhe DofCom)
1: .--.] -|: l--- .|--: ----:--l-
l- ':l.l-' - -.: :-|| - l- l-lc--':
|-:.l-- :-||: .--.] |-- -.-|-, l-
:-|| .l -- i : l, l-- :-l -- i -
l- lc-||:' .--.] l- 'l---'
faIse
true
fixing the bug
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 129
We couId jusf keep fhe one originoI orroy, buf chonge fhe voIue of ony hif
ceIIs fo -I. Thof woy, we onIy hove OME orroy fo check ond monipuIofe
2
0p!|en ! we
0p!|en enc |s !ee r|enky
Opfion one seems Iike more work fhon you'd expecf. If meons fhof eoch
fime fhe user mokes o hif, you hove fo chonge fhe sfofe of fhe second
orroy (fhe 'hifCeIIs' orroy), oh -- buf frsf you hove fo CHECI fhe 'hifCeIIs'
orroy fo see if fhof ceII hos oIreody been hif onywoy. If wouId work, buf
fhere's gof fo be somefhing beffer...
0 I Z
IocutionCeIIs
(insfonce voriobIe of
fhe DofCom)
. ~| .l . .-l:-|.- :-|| |-:.l-- --.-: l.l l- :-||
.: .|--.] --- l, :- --'-- --|] |--- -- ---~
--.l- -----: - l- .--.]
Opfion fwo is o IiffIe Iess cIunky fhon opfion one, buf if's nof very effcienf. You'd
sfiII hove fo Ioop fhrough oII fhree sIofs (index posifions) in fhe orroy, even if
one or more ore oIreody invoIid becouse fhey've been 'hif' (ond hove o -I voIue).
There hos fo be somefhing beffer...
0p!|en ! we |s z || !!|c |c!!cr, |e!
s!|| | prc!!y r|enky
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
130 chapter 6
REPEAY .|t| oac| o t|o |ocat|oo co||s |o t|o aa
// CC/|^| t|o oso gooss to t|o |ocat|oo co||
IF t|o oso gooss atc|os
INCREMENY t|o oobo o ||ts
// |` CJ | |t .as t|o |ast |ocat|oo co||.
IF oobo o ||ts |s 3, REYURN ''|||'
EL5E |t .as oot a '|||, so REYURN'||t'
||| ||
EL5E oso gooss o|o oot atc|, so REYURN '|ss'
||| ||
||| ||||/T
REPEAY .|t| oac| o t|o |ocat|oo co||s
// CC/|^| t|o oso gooss to t|o |ocat|oo co||
IF t|o oso gooss atc|os
REMOVE t||s co|| o t|o aa
// |` CJ | |t .as t|o |ast |ocat|oo co||.
IF t|o aa |s oo. opt, REYURN ''|||'
EL5E |t .as oot a '|||, so REYURN'||t'
||| ||
EL5E oso gooss o|o oot atc|, so REYURN '|ss'
||| ||
||| ||||/T
Ihc er|]|nz| prcpre4c fer pzr! ef !hc
rhcrkYeersc|f|I mc!he4:
I|fc wee|4 |c ]ee4 |f en|y wc ree|4
rhzn]c | ! !e:
prep code test code reaI code prep code
We deIefe eoch ceII Iocofion os if gefs hif, ond fhen modify fhe orroy fo
be smoIIer. Excepf orroys con'f chonge fheir si;e, so we hove fo moke o
new orroy ond copy fhe remoining ceIIs from fhe oId orroy info fhe new
smoIIer orroy.
3
0p!|en !hrcc
0 I Z
IocutionCeIIs urruy
8EFOPE ony ceIIs
hove been hif
1- .--.] :l.-l: --l -l . :-- - ?, .- -- |-- l--- .|| ? :-||: |-:l--: - l- .--.]` l- |-- -- . -.l: -l---- l- -:-- --:: .- l- :-|| .|-- |+,-, |`
w-- :-|| '-' : l, -- -.- . ---, :-.||-- .--.] -l --|] l- ---.-~ - :-|| |-:.l--:, .- .::- l l- l- ---.| |-:.l--c-||: ------:-
IocutionCeIIs urruy
AFTEP ceII 'b', which
wos of index I in fhe
orroy, hos been hif
0 I
0p!|en !hrcc wee|4 |c merh |c!!cr |f !hc zrrzy ree|4 shr|nk, se !hz! wc wee|4n! hzvc
!e mzkc z ncw smz||cr zrrzy, repy !hc rcmz|n|n] vz|ecs |n, zn4 rczss|]n !hc rcfcrcnrc.
prep code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 131
If onIy I couId fnd on orroy
fhof couId shrink when you remove
somefhing. And one fhof you didn'f hove
fo Ioop fhrough fo check eoch eIemenf, buf
insfeod you couId jusf usk it if it contuins
whof you're Iooking for. And if wouId Ief you
get fhings ouf of if, wifhouf hoving fo know
exocfIy which sIof fhe fhings ore in.
Thof wouId be dreomy. 8uf I know if's
jusf o fonfosy...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
when arrays aren't enough
132 chapter 6
Wzkc ep zn4 smc| | !hc |||rzry
As if by magic, there really is such a thing.
But it's not an array, it's an ArrayList.
A class in the core Java library {the AP}.
Thc ]ava Sianuaiu Euiiion which is whai you havc unlcss you`ic woiI-
ing on ihc Micio Euiiion loi small ucviccs anu lclicvc mc, ,ou`J Irow)
shis wiih hunuicus ol ic-luili classcs. ]usi liIc oui Rcauy-BaIc couc
cxcci ihai ihcsc luili-in classcs aic alicauy comilcu.
Thot meons no typing.
]usi usc cm.
6-- - . .-||-- :|.::-: -
l- ).. |-.-]
/-- :.- -:- l - ]--- :--
.: ]-- ---l- l ]---:-|
ArrayList
add(D
bject eIem
)
rem
ove(int index)
rem
ove(D
bject eIem
)
contains(D
bject eIem
)
ism
pty()
indexD
f(D
bject eIem
)
size()
get(int index)
Adds the ob|ect parameter to the list.
Pemoves the ob|ect at the index parameter.
Peturns 'true' if there's a match for the ob|ect parameter
Peturns 'true' if the list has no elements
Peturns either the index of the ob|ect parameter, or -l
Peturns the number of elements currently in the list
Peturns the ob|ect currently at the index parameter
Pemoves this ob|ect (if it's in the ArrayList).
|N-l- l- .|6-:l -|--` --l-
.:l-.||] |--: . |ll|- :l-.--- l.- l-
--- --'- :--- --- --'|| -l l- l-
--.| --- |.l-- - l- -- |-- ---, -:l
l- - l .: .- .|` --l- l.l
l.-: l- --:l ]-- -.-l l- .`
1: : -:l . :.-|- - 6M! -
l- --l-: - A--.]|:l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
get to know the Java API
you are here 133
8emc !h|n]s yee rzn 4e w| !h rrzyI|s!
1 Moke one
ArrayList<Egg> myList = new ArrayList<Egg>();
2 Puf somefhing in if
Egg s = new Egg();
myList.add(s);
7
Pemove somefhing from if
myList.remove(s);
4 Find ouf how mony fhings ore in if
int theSize = myList.size();
5 Find ouf if if confoins somefhing
boolean isIn = myList.contains(s);
6
Find ouf if if's empfy
boolean empty = myList.isEmpty();
Find ouf where somefhing is (i.e. ifs index)
int idx = myList.indexOf(b);
8
3 Puf onofher fhing in if
Egg b = new Egg();
myList.add(b);
A --- A--.]|:l --:l :
:--.l- -- l- -. |l': |ll|-
-:.-:- l': --l]
N-- l- A--.]|:l ---: . -'
l- -| l- ! --:l
1- A--.]|:l ---: ..- l- -|
l- :-:-- ! --:l
1- A--.]|:l : -|- i --:l: :-
l- :--|` --l- --l---: i
1- A--.]|:l l6! :--l.- l- ! --:l
------:- ] ':', :- :--l.-:|` --l---: l---
A--.]|:l : ----~.:- |--.-: -:l -- : o`
.- :-:- l- --:l ------:- ] '' -.: l-
:-:-- l- - l- |:l, --6|` --l---: |
l': --l-|] N61 --l], :- :!-l]|`
--l---: .|:-
+-] |-- - l :-.-'
l--'l ----] .--l l: --- ! .-|-~-.:-l :]-l.
-l ---. l -:l --.-: -.- l: . |:l - ! --:l:'
:
:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
when arrays aren't enough
134 chapter 6
+,-+ :+ ,-+:.|
ArrayList<String> myList = new
ArrayList<String>();
l-- |1 -]|:l = --- l--|i1.
String a = new String(whoohoo);
l-- . = --- l--|-----'`.
myList.add(a);
String b = new String(Frog);
l-- = --- l--||--'`.
myList.add(b);
int theSize = myList.size();
Object o = myList.get(1);
myList.remove(1);
boolean isIn = myList.contains(b);
rrzyI|s! rc]e|zr zrrzy
Pill in the rest of the table below by looking at the ArrayList code
on the left and putting in what you think the code might be if it
were using a regular array instead. we don't expect you to get all
of them exactly right, so |ust make your best guess.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 135
(-,- a,- |
oa|| qa--(:|-
C
D
F
C
0 1 2 3 4 5 6
AskMe.com
Pets.com
C
o
2
.
c
o
m
:l.-l: .l ----, |- ).. .--.]:
pzr! ef z ]zmc |n!crzr!|en
You're going to build the
Sink a Dot Com game, with
a 7 x 7 grid and three
Dot Coms. Each Dot Com
takes up three cells.
-.: -
: . :-||'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 141
Whz! ncc4s !e rhzn]c!
Wc havc ihicc classcs ihai nccu io changc: ihc
DoiCom class which is now callcu DoiCom insicau ol
SimlcDoiCom), ihc gamc class DoiComBusi) anu ihc
gamc hclci class which wc won`i woiiy aloui now).
DotCom class
Add a nome variablc
io holu ihc namc ol ihc DoiCom
Pcis.com", Go2.com", cic.) so cach Doi-
Com can iini iis namc whcn ii`s Iillcu scc
ihc ouiui sciccn on ihc oosiic agc).
DotComBust class continued...
Put thc DotComs on a grid rathcr than
just a singlc row, and do it Ior all thrcc
DotComs.
This sic is now way moic comlcx ihan
lcloic, il wc`ic going io lacc ihc DoiComs
ianuomly. Sincc wc`ic noi hcic io mcss
wiih ihc maih, wc ui ihc algoiiihm loi
giving ihc DoiComs a locaiion inio ihc
GamcHclci Rcauy-laIc) class.
Chcck cach uscr gucss with oII three
DotComs, instcad oI just onc.
Kccp playing thc gamc i.c accciing
usci gucsscs anu chccIing ihcm wiih ihc
icmaining DoiComs) untiI there ore no more
Iive DotComs.
Gct out oI main. Wc Ici ihc simlc onc in
main |usi io... Icc ii simlc. Bui ihai`s noi
whai wc wani loi ihc gamc.
0ot6omust
The game c|ass.
Va|es 0olCors,
els user |rpul,
p|ays url|| a|| 0ol-
Cors are dead
0ot6om
The actua|
0ot6om objects.
0olCors |roW l|e|r
rare, |ocal|or, ard
|oW lo c|ec| a user
uess lor a ralc|.
3 Classes:
Camehe|per
The he|per c|ass
(Ready-8a|e).
ll |roWs |oW lo
accepl user cor-
rard-||re |rpul,
ard ra|e 0olCor
|ocal|ors.
5 Ob]ects:
DofCom8usf
DofCom
DofCom
DofCom
0omeHeIper
u
s
e
s
f
o
r
p
Io
y
e
r
in
p
u
f ond fo moke D
o
f
C
o
m
Io
c
o
f
i
o
n
s
c
r
e
o
fes ond pIoys wif
h
DotComBust class {the game}
Crcatc three DotComs instcad oI onc.
Givc cach oI thc thrcc DotComs a nome.
Call a sciici mcihou on cach DoiCom
insiancc, so ihai ihc DoiCom can assign ihc
namc io iis namc insiancc vaiiallc.
PIus 4
ArroyLisfs: I for
fhe DofCom8usf
ond I for eoch
of fhe 3 DofCom
objecfs.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
142 chapter 6
Whe 4ecs whz! |n !hc Pe!0emBes! ]zmc
|zn4 whcnI
insfonfiofes
The DofCom8usf (gome)
objecf insfonfiofes on
insfonce of 0omeHeIper,
fhe objecf fhof wiII heIp
fhe gome do ifs work.
leljer
DofCom8usf
objecf
0omeHeIper
objecf
ArroyLisf objecf fo
hoId DofCom objecfs
The DofCom8usf objecf
creofes fhree DofCom
objecfs (ond pufs fhem in
fhe ArroyLisf)
leljer
ie|Cem:|i:|
DofCom8usf
objecf
0omeHeIper
objecf
ie|Cem
J
ie|Cem
I
ie|Cem
Z
tell:
tell:
tell:
DofCom
objecfs
ArroyLisf objecf fo
hoId DofCom objecfs
The DofCom8usf objecf osks fhe
heIper objecf for o Iocofion for o
DofCom (does fhis 3 fimes, one for
eoch DofCom)
leljer
ie|Cem:|i:|
DofCom8usf
objecf
0omeHeIper
objecf
m
o
k
e
Io
cofion
ie|Cem
J
ie|Cem
I
ie|Cem
Z
tell:
tell:
tell:
DofCom
objecfs
h
e
re
if is
The DofCom8usf objecf gives eoch of fhe Dof-
Com objecfs o Iocofion (which fhe DofCom8usf
gof from fhe heIper objecf) Iike "AZ", "8Z",
efc. Eoch DofCom objecf pufs his own fhree
Iocofion ceIIs in on ArroyLisf
ArroyLisf objecf
(fo hoId DofCom
ceII Iocofions)
tell
J
tell
I
tell
Z
ArroyLisf
objecf
ArroyLisf
objecf
tell
J
tell
I
tell
Z
tell
J
tell
I
tell
Z
ArroyLisf objecf fo
hoId DofCom objecfs
The DofCom8usf objecf osks fhe heIper
objecf for o user guess (fhe heIper
prompfs fhe user ond gefs inpuf from
fhe commond-Iine)
leljer
ie|Cem:|i:|
DofCom8usf
objecf
0omeHeIper
objecf
g
e
f
u
s
er guess
ie|Cem
J
ie|Cem
I
ie|Cem
Z
tell:
tell:
tell:
DofCom
objecfs
c
h
e
c
k
f
h
is
g
u
ess
h
e
re
if is
ArroyLisf objecf
(fo hoId DofCom
ceII Iocofions)
tell
J
tell
I
tell
Z
ArroyLisf
objecf
ArroyLisf
objecf
tell
J
tell
I
tell
Z
tell
J
tell
I
tell
Z
"h
if"
The DofCom8usf objecf Ioops fhrough fhe Iisf
of DofComs, ond osks eoch one fo check fhe user
guess for o mofch. The DofCom checks ifs Iocofions
ArroyLisf ond refurns o resuIf ("hif", "miss", efc.)
And so fhe gome confinues... gef-
fing user inpuf, osking eoch DofCom
fo check for o mofch, ond confinuing
unfiI oII DofComs ore deod
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
144 chapter 6
0arele|per |e|per
ArrayL|sl dolCorsL|sl
|rl rur0l0uesses
selup0are()
slarlP|ay|r()
c|ec|user0uess()
l|r|s|0are()
prep code test code reaI code prep code
DECLARE aoo |ostaot|ato t|o ComeHe|per |ostaoco va|ab|o, oaoo he|per.
DECLARE aoo |ostaot|ato ao Arro,L|st to |o|o t|o ||st o |otCos (|o|t|a|| t|oo) Ca|| |t
dotComsL|st.
DECLARE ao |ot va|ab|o to |o|o t|o oobo o oso goossos (so t|at .o cao g|vo t|o oso a
scoo at t|o ooo o t|o gao). |ao |t num0fCuesses aoo sot |t to 0.
DECLARE a setUpCome(j ot|oo to coato aoo |o|t|a||zo t|o |otCo ob,octs .|t| oaos
aoo |ocat|oos. ||sp|a b|o |ostoct|oos to t|o oso.
DECLARE a stortP|o,|ng(j ot|oo t|at as's t|o p|ao o goossos aoo ca||s t|o
c|oc'|soCooss() ot|oo oot|| a|| t|o |otCo ob,octs ao oovoo o p|a.
DECLARE a checkUserCuess(j ot|oo t|at |oops t|oog| a|| oa|o|og |otCo ob,octs aoo
ca||s oac| |otCo ob,oct's c|oc'Yooso|() ot|oo.
DECLARE a f n|shCome(j ot|oo t|at p|ots a ossago aboot t|o oso's pooaoco, basoo
oo |o. ao goossos |t too' to s|o' a|| o t|o |otCo ob,octs.
MEYHOD. voId setUpGome()
// o'e tee ctCc c!,ects o! oe te
CREAYE t|oo |otCo ob,octs.
5EY a oao o oac| |otCo.
ADD t|o |otCos to t|o dotComsL|st ( t|o /a||st).
REPEAY .|t| oac| o t|o |otCo ob,octs |o t|o dotComsL|st aa
CALL t|o p|oceuotCom(j ot|oo oo t|o |o|po ob,oct, to got a aooo|-so|octoo
|ocat|oo o t||s |otCo (t|oo co||s, vot|ca|| o |o|zoota|| a||gooo, oo a g|o).
5EY t|o |ocat|oo o oac| |otCo basoo oo t|o oso|t o t|o p|oceuotCom(j ca||.
||| ||||/T
||| ||TC|
Thc DoiComBusi class has ihicc main |ols: sci u ihc gamc, lay ihc gamc
uniil ihc DoiComs aic ucau, anu cnu ihc gamc. Alihough wc coulu ma
ihosc ihicc |ols uiiccily inio ihicc mcihous, wc slii ihc miuulc |ol lay ihc
gamc) inio mcihous, io Icc ihc gianulaiiiy smallci. Smallci mcihous
mcaning smallci chunIs ol lunciionaliiy) hcl us icsi, uclug, anu mouily
ihc couc moic casily.
|rcp re4c fer !hc rcz| Pe!0emBes! r|zss
Variable
Declarations
Method
Declarations
Method
mplementations
the DotComBust cIass (the game)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 145
MEYHOD. voId checkUserGuess(StrIng userGuess)
// (! c.t , tees o t (o! ''') c o, ctCc
INCREMENY t|o oobo o oso goossos |o t|o num0fCuesses va|ab|o
5EY t|o |oca| resu|t va|ab|o (a Str|ng) to '|ss', asso|og t|at t|o oso's gooss .||| bo a |ss.
REPEAY .|t| oac| o t|o |otCb,octs |o t|o dotComsL|st aa
EVALUAYE t|o oso's gooss b ca|||og t|o |otCo ob,oct's checkourse|f(j ot|oo
5EY t|o oso|t va|ab|o to '||t' o ''|||' | appop|ato
IF t|o oso|t |s ''|||', REMOVE t|o |otCo o t|o dotComsL|st
||| ||||/T
DI5PLAY t|o resu|t va|oo to t|o oso
||| ||TC|
MEYHOD. voId nIshGome()
DI5PLAY a gooo|c 'gao ovo' ossago, t|oo.
IF oobo o oso goossos |s sa||,
DI5PLAY a coogato|at|oos ossago
EL5E
DI5PLAY ao |oso|t|og ooo
||| ||
||| ||TC|
prep code test code reaI code prep code
MEYHOD. voId stortPIoyIng()
REPEAY .|||o ao |otCos o|st
GEY oso |opot b ca|||og t|o |o|po getUserlnput(j ot|oo
EVALUAYE t|o oso's gooss b checkUserCuess(j ot|oo
||| ||||/T
||| ||TC|
Mc!he4 |mp|cmcn!z!|ens ren!|nec4:
+,-+ :+ ,-+:.|
How should we go from prep code to the
final codeI Pirst we start with test code, and
then test and build up our methods bit by
bit. we won't keep showing you test code
in this book, so now it's up to you to think
about what you'd need to know to test these
methods. And which method do you test
and write firstI See if you can work out some
prep code for a set of tests. Prep code or
even bullet points are good enough for this
exercise, but if you want to try to write the
test code (in 1ava), knock yourself out.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
146 chapter 6
import java.util.*;
public class DotComBust {
private GameHelper helper = new GameHelper();
private ArrayList<DotCom> dotComsList = new ArrayList<DotCom>();
private int numOfGuesses = 0;
private void setUpGame() {
// h rst make some dot coms and give them locations
DotCom one = new DotCom();
one.setName(Pets.com);
DotCom two = new DotCom();
two.setName(eToys.com);
DotCom three = new DotCom();
three.setName(Go2.com);
dotComsList.add(one);
dotComsList.add(two);
dotComsList.add(three);
System.out.println(Your goal is to sink three dot coms.);
System.out.println(Pets.com, eToys.com, Go2.com);
System.out.println(Try to sink them all in the fewest number of guesses);
for (DotCom dotComToSet : dotComsList) {
ArrayList<String> newLocation = helper.placeDotCom(3);
dotComToSet.setLocationCells(newLocation);
} // close for loop
} // close setUpGame method
private void startPlaying() {
while(!dotComsList.isEmpty()) {
String userGuess = helper.getUserInput(Enter a guess);
checkUserGuess(userGuess);
} // close while
h nishGame();
} // close startPlaying method
prep code test code reaI code reaI code
1
2
3
4
5
6
10
9
.: |-- .: l- l-lc--
|:l : N61 --l]
-l -:-- --l
:.|| --- --- :-:c:--6--:: --l-
:.|| --- --- -:6.-- --l-
--l --
-:l--:l--: --
-:--
-:|.-- .- -l.|--
l- .-.|-: --'|| ---
---.l -l -.: l-lc-- - l- |:l
-.- l--- l-lc-- --:l:, - '--
-.--:, .- :l: '-- - l- A--.]|:l
.: l- -|-- -- . l-lc-- |-:.l--
:.|| l- :-ll-- --l- -- l: l-lc--
l- - l l- |-:.l-- ]-- -:l -l
--- l- -|--
+,-+ :+ ,-+:.|
Annotate the code
yourselfl
Match the
annotations at the
bottom of each page
with the numbers
in the code. Write
the number in the
slot in front of the
corresponding
annotation.
You'll use each
annotation ]ust once,
and you'll need all of
the annotations.
the DotComBust code (the game)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 147
private void checkUserGuess(String userGuess) {
numOfGuesses++;
String result = miss;
for (DotCom dotComToTest : dotComsList) {
result = dotComToTest.checkYourself(userGuess);
if (result.equals(hit)) {
break;
}
if (result.equals(kill)) {
dotComsList.remove(dotComToTest);
break;
}
} // close for
System.out.println(result);
} // close method
private void nishGame() {
System.out.println(All Dot Coms are dead! Your stock is now worthless.);
if (numOfGuesses <= 18) {
System.out.println(It only took you + numOfGuesses + guesses.);
System.out.println( You got out before your options sank.);
} else {
System.out.println(Took you long enough. + numOfGuesses + guesses.);
System.out.println(Fish are dancing with your options.);
}
} // close method
public static void main (String[] args) {
DotComBust game = new DotComBust();
game.setUpGame();
game.startPlaying();
} // close method
}
-:-----l l- ----- - --::-: l- -:-- .: -.-
.::--- l': . '-::', --|-:: l-| -l---:-
---.l -l .|| l-lc--: - l- |:l
.: l- l-lc-- l- :-: l- -:-- --::,
|--- -- . l |-- ||`
-l --l - l- |--
-.-|], -- --l - l-:l-
l- -l--:
l: -]': -., :- l.- - --l - l-
l-lc--: |:l l-- -l --l - l- |--
--l l-
--:-|l --
l- -:--
--l . --::.- l-||- l-
-:-- -- - - l- .--
l-|| l- .-- --:l l- :l.-l l- -.-
.-- |.] |-- |--: .:- -- -:--
--l .- :-:- l- --::`
prep code test code reaI code reaI code
12
13
14
15
16
17
18
19
20
21
l-|| l- .-- --:l
l- :-l - l- .--
:--.l- l- .-- --:l
11
Whatever you do,
DON'T turn the
pagel
Not until you've
hnished this
exercise.
Our version is on
the next page.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
148 chapter 6
import java.util.*;
public class DotComBust {
private GameHelper helper = new GameHelper();
private ArrayList<DotCom> dotComsList = new ArrayList<DotCom>();
private int numOfGuesses = 0;
private void setUpGame() {
// h rst make some dot coms and give them locations
DotCom one = new DotCom();
one.setName(Pets.com);
DotCom two = new DotCom();
two.setName(eToys.com);
DotCom three = new DotCom();
three.setName(Go2.com);
dotComsList.add(one);
dotComsList.add(two);
dotComsList.add(three);
System.out.println(Your goal is to sink three dot coms.);
System.out.println(Pets.com, eToys.com, Go2.com);
System.out.println(Try to sink them all in the fewest number of guesses);
for (DotCom dotComToSet : dotComsList) {
ArrayList<String> newLocation = helper.placeDotCom(3);
dotComToSet.setLocationCells(newLocation);
} // close for loop
} // close setUpgame method
private void startPlaying() {
while(!dotComsList.isEmpty()) {
String userGuess = helper.getUserInput(Enter a guess);
checkUserGuess(userGuess);
} // close while
h nishGame();
} // close startPlaying method
prep code test code reaI code reaI code
l-:|.-- .- -l.|--
l- .-.|-: --'|| ---
M.- l--- l-lc-- --:l:,
- '-- -.--:, .- :l: '--
- l- A--.]|:l
|--l --
-:l--:l--: -- -:--
A: l- -|-- -- .
l-lc-- |-:.l-- |.-
A--.]|:l - l--:`
c.|| l- :-ll-- --l- -- l: l-lc-- l- - l l- |-:.l-- ]--
-:l -l --- l- -|--
--.l -l -.: l-lc-- - l- |:l
A: |-- .: l- l-lc-- |:l : N61 --l] |l- ' --.-: N61, l':
l- :.-- .: |-lc--:|:l:!-l]|` == .|:-`
6-l -:-- --l
c.|| --- --- :-:c:--6--:: --l-
c.|| --- --- -:6.-- --l-
the DotComBust code (the game)
M.- .- A--.]|:l -
l-lc-- --:l: |- -l--
---:, . |:l l.l -|| -|
6N|/ l-lc-- --:l:,
-:l .: l-lc--|1 ---|
--.- .- .--.] - l-lc--
--:l:`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 149
private void checkUserGuess(String userGuess) {
numOfGuesses++;
String result = miss;
for (DotCom dotComToTest : dotComsList) {
result = dotComToTest.checkYourself(userGuess);
if (result.equals(hit)) {
break;
}
if (result.equals(kill)) {
dotComsList.remove(dotComToTest);
break;
}
} // close for
System.out.println(result);
} // close method
private void nishGame() {
System.out.println(All Dot Coms are dead! Your stock is now worthless.);
if (numOfGuesses <= 18) {
System.out.println(It only took you + numOfGuesses + guesses.);
System.out.println( You got out before your options sank.);
} else {
System.out.println(Took you long enough. + numOfGuesses + guesses.);
System.out.println(Fish are dancing with your options);
}
} // close method
public static void main (String[] args) {
DotComBust game = new DotComBust();
game.setUpGame();
game.startPlaying();
} // close method
}
-:-----l l- ----- - --::-: l- -:-- .: -.-
.::--- l': . '-::', --|-:: l-| -l---:-
---.l -l .|| l-lc--: - l- |:l
.: l- l-lc-- l- :-: l- -:--
--::, |--- -- . l |-- ||`
-l --l - l- |-- -.-|], -- --l
- l-:l- l- -l--:
l: -]': -., :- l.- - --l - l-
l-lc--: |:l l-- -l --l - l- |--
--l l- --:-|l -- l- -:--
--l . --::.- l-||- l-
-:-- -- - - l- .--
:--.l- l- .-- --:l
l-|| l- .-- --:l l- :-l - l- .--
l-|| l- .-- --:l l- :l.-l l- -.-
.-- |.] |-- |--: .:- -- -:--
--l .- :-:- l- --::`
prep code test code reaI code reaI code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
150 chapter 6
import java.util.*;
public class DotCom {
private ArrayList<String> locationCells;
private String name;
public void setLocationCells(ArrayList<String> loc) {
locationCells = loc;
}
public void setName(String n) {
name = n;
}
public String checkYourself(String userInput) {
String result = miss;
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = kill;
System.out.println(Ouch! You sunk + name + : ( );
} else {
result = hit;
} // close if
} // close if
return result;
} // close method
} // close class
l-lc--': -:l.-:- .-.|-:
~ .- A--.]|:l - :-|| |-:.l--:
~ l- l-lc--': -.--
A :-ll-- --l- l.l -.l-:
l- l-lc--': |-:.l--
|.--- |-:.l-- --- ]
l- 6.--+-|-- |.:-l-lc--| `
--l-`
/--- .:: :-ll-- --l-
1- A--.]|:l --6| ` --l- -
.:l--' | l- -:-- --:: : --- - l-
--l--: - l- A--.]|:l, --6| `
-|| --l--- l: A--.]|:l |-:.l-- |
--l, --6| ` -|| --l--- ~|
1-|| l- -:-- --- . l-lc-- .: --- :--
c:- l- :!-l]| ` --l- l- :-- .||
- l- |-:.l--: .- --- --::-
c:- A--.]|:l': -----| ` --l- l- -|-l- .- --l-]
Ihc f|nz| vcrs|en ef !hc
Pe!0em r|zss
-l--- '-::' -- 'l' -- '||'
prep code test code reaI code reaI code
the DotCom code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 151
8epcr |ewcrfe| Bee|czn Irprcss|ens
So far, when we've used boolean expressions for our loops or
tests, they've been pretty simple. we will be using more
powerful boolean expressions in some of the Peady-8ake code
you're about to see, and even though we know you wouldn't
peek, we thought this would be a good time to discuss how to
energize your expressions.
And' and Or' Operators { &&, || }
Let's say you're writing a chooseCamera( ) method, with lots of rules
about which camera to select. Maybe you can choose cameras
ranging from $50 to $l000, but in some cases you want to limit the
price range more precisely. ou want to say something like:
'|f the price tone is between $300 nnJ $400 then choose X.'
if {price >= 300 && price < 400} [
camera = "X",
]
Let's say that of the ten camera brands available, you have some
logic that applies to only a lew of the list:
if {brand.eguals{"A"} [[ brand.eguals{"B"} } [
// do stuff for brand A brand B
]
8oolean expressions can get really big and complicated:
if {{zoomType.eguals{"optical"} &&
{zoomDegree >= 3 && zoomDegree <= 8}} [[
{zoomType.eguals{"digital"} &&
{zoomDegree >= 5 && zoomDegree <= 12}}} [
// do appropriate zoom stuff
]
|f you want to get teolly technical, you might wonder about the
teceJence of these operators. |nstead of becoming an expert
in the arcane world of precedence, we recommend that you use
nrenrheses to make your code clear.
Not equals { l= and l }
Let's say that you have a logic like, "of the ten available
camera models, a certain thing is ttue lot oll out one. "
if {model != 2000} [
// do non-model 2000 stuff
]
or for comparing ob|ects like strings...
if {!brand.eguals{"X"}} [
// do non-brand X stuff
]
8hort Circuit Operators { && , || }
The operators we've looked at so far, && and ||, are
known as sherr circuir operators. |n the case of &&,
the expression will be true only if ooth sides of the &&
are true. So if the 1vM sees that the left side of a &&
expression is false, it stops right there! Doesn't even
bother to look at the right side.
Similarly, with ||, the expression will be true if e|thet side is
true, so if the 1vM sees that the left side is true, it declares
the entire statement to be true and doesn't bother to
check the right side.
why is this greatI Let's say that you have a reference
variable and you're not sure whether it's been assigned
to an ob|ect. |f you try to call a method using this null
reference variable (i.e. no ob|ect has been assigned), you'll
get a NullPointerLxception. So, try this:
if {refVar != null &&
refVar.isValidType{} } [
// do 'got a valid type' stuff
]
Non 8hort Circuit Operators { & , | }
when used in boolean expressions, the & and | operators
act like their && and || counterparts, except that
they force the 1vM to olwoys check ooth sides of the
expression. Typically, & and | are used in another context,
for manipulating bits.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
152 chapter 6
import java.io.*;
import java.util.*;
public class {
private static h nal String alphabet = abcdefg;
private int gridLength = 7;
private int gridSize = 49;
private int [] grid = new int[gridSize];
private int comCount = 0;
public String getUserInput(String prompt) {
String inputLine = null;
System.out.print(prompt + );
try {
BufferedReader is = new BufferedReader(
new InputStreamReader(System.in));
inputLine = is.readLine();
if (inputLine.length() == 0 ) return null;
} catch (IOException e) {
System.out.println(IOException: + e);
}
return inputLine.toLowerCase();
}
public ArrayList<String> placeDotCom(int comSize) {
ArrayList<String> alphaCells = new ArrayList<String>();
String [] alphacoords = new String [comSize]; // holds `f6' type coords
String temp = null; // temporary String for concat
int [] coords = new int[comSize]; // current candidate coords
int attempts = 0; // current attempts counter
boolean success = false; // H ag = found a good location ?
int location = 0; // current starting location
comCount++; // nth dot com to place
int incr = 1; // set horizontal increment
if ((comCount % 2) == 1) { // if odd dot com (place vertically)
incr = gridLength; // set vertical increment
}
while ( !success & attempts++ < 200 ) { // main search loop (32)
location = (int) (Math.random() * gridSize); // get random starting point
//System.out.print(` try ` + location);
int x = 0; // nth position in dotcom to place
success = true; // assume success
while (success && x < comSize) { // look for adjacent unused spots
if (grid[location] == 0) { // if not already used
0zsJj-hskz
0aJz
This is fhe heIper cIoss for fhe gome. 8esides fhe user inpuf mefhod
(fhof prompfs fhe user ond reods inpuf from fhe commond-Iine), fhe
heIper's 8ig Service is fo creofe fhe ceII Iocofions for fhe DofComs.
If we were you, we'd jusf bock owoy sIowIy from fhis code, excepf
fo fype if in ond compiIe if. We fried fo keep if foirIy smoII fo you
wouIdn'f hove fo fype so much, buf fhof meons if isn'f fhe mosf
reodobIe code. And remember, you won'f be obIe fo compiIe fhe
DofCom8usf gome cIoss unfiI you hove fhis cIoss.
N-l- |-- -l-. :--l, ]-- -l
l-] '--~:-----l-' l-
]:l----l--l||-`': - l-
|.:-l-lc--| ` --l-, -:l
l- -.l: l ---' 1-:- --l
:l.l----l: -|| |-l ]-- :-.l'
] - ]-- l- |-:.l-- - l-
l-lc--:, -l l -|| -| ]-- l-:l l
Ready-bake: GameHeIper
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
get to know the Java API
you are here 153
coords[x++] = location; // save location
location += incr; // try `next' adjacent
if (location >= gridSize){ // out of bounds - `bottom'
success = false; // failure
}
if (x>0 && (location % gridLength == 0)) { // out of bounds - right edge
success = false; // failure
}
} else { // found already used location
// System.out.print(` used ` + location);
success = false; // failure
}
}
} // end while
int x = 0; // turn location into alpha coords
int row = 0;
int column = 0;
// System.out.println(`\n");
while (x < comSize) {
grid[coords[x]] = 1; // mark master grid pts. as `used'
row = (int) (coords[x] / gridLength); // get row value
column = coords[x] % gridLength; // get numeric column value
temp = String.valueOf(alphabet.charAt(column)); // convert to alpha
alphaCells.add(temp.concat(Integer.toString(row)));
x++;
// System.out.print(` coord `+x+" = ` + alphaCells.get(x-1));
}
// System.out.println(`\n");
return alphaCells;
}
}
0zsJj-hskz
0aJz
0zmcHc|pcr r|zss re4c ren!|nec4...
1: : l- :l.l----l l.l
l-||: ]-- -.:l|] ---- l-
l-lc-- : |-:.l-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
154 chapter 6
API packages
0s|n] !hc I||rzry |!hc 1zvz ||I
n the Java AP, classes
are grouped into packages.
To use a class in the AP, you
have to know which package
the class is in.
Evciy class in ihc ]ava liliaiy lclongs io a acIagc.
Thc acIagc has a namc, liIc javax.swing a
acIagc ihai holus somc ol ihc Swing GUI classcs
you`ll lcain aloui soon). AiiayIisi is in ihc acIagc
callcu java.utiI, which suiiisc suiiisc, holus a
ilc ol u.I., classcs. You`ll lcain a loi moic aloui
acIagcs in chaici 16, incluuing how io ui youi
owr classcs inio youi owr acIagcs. Ioi now ihough,
wc`ic |usi looIing io ue somc ol ihc classcs ihai comc
wiih ]ava.
Using a class liom ihc API, in youi own couc, is
simlc. You |usi iicai ihc class as ihough you wioic
ii youiscll... as ihough you comilcu ii, anu ihcic ii
siis, waiiing loi you io usc ii. Wiih onc lig uillcicncc:
somcwhcic in youi couc you havc io inuicaic ihc uII
namc ol ihc liliaiy class you wani io usc, anu ihai
mcans acIagc namc + class namc.
Evcn il you uiun`i Inow ii, you`ve oIreody been using
cIosses [rom o pochoge. Sysicm Sysicm.oui.iiniln),
Siiing, anu Maih Maih.ianuom)), all lclong io ihc
java.Iang acIagc.
You mauc ii all ihc way ihiough ihc DoiComBusi gamc,
ihanIs io ihc hcl ol AiiayIisi. Anu now, as iomiscu,
ii`s iimc io lcain how io lool aiounu in ihc ]ava liliaiy.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 155
import java.util.ArrayList;
public class MyClass {... }
You have to know the full name*
of the class you want to use in
your code.
AiiayIisi is noi ihc namc ol AiiayIisi, |usi as Kaihy`
isn`i a lull namc unlcss ii`s liIc Mauonna oi Chci, lui wc
won`i go ihcic). Thc lull namc ol AiiayIisi is aciually:
java.util.ArrayList
You have to tell Java which ArrayList you
want to use. You have two options:
MPORT
TYPE
java.util.ArrayList<Dog> list = new java.util.ArrayList<Dog>();
Type the full name everywhere in your code. Each time
you use it. you use it.
OR
Put an import statement at the top of your source code fle:
Browse a Book
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
get to know the Java API
you are here 159
Browse a Book
FIipping fhrough o
reference book is fhe
besf woy fo fnd ouf
whof's in fhe Jovo
Iibrory. You con eosiIy
sfumbIe on o cIoss fhof
Iooks usefuI, jusf by
browsing poges.
.:.- -.--
:|.:: -.--
:|.:: -::-l--
--l-: |.- -l-- l-:
--'|| l.| .--l |.l--`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
160 chapter 6
using the Java API documentation
CaJe Kagaets
if (a.contains(three)) {
a.add(four);
}
import java.util.*;
public class ArrayListMagnet {
ArrayList<String> a = new ArrayList<String>();
public static void main (String[] args) {
a.add(0,zero);
a.add(1,one);
a.add(2,two);
a.add(3,three);
printAL(a);
a.remove(2);
if (a.indexOf(four) != 4) {
a.add(4, 4.2);
}
if (a.contains(two)) { a.add(2.2);
}
public static void printAL(ArrayList<String> al) {
for (String element : al) {
System.out.print(element + );
}
System.out.println( );
}
}
}
printAL(a);
printAL(a);
printAL(a);
File Edit Window Help Dance
% java ArrayListMagnet
zero one two three
zero one three four
zero one three four 4.2
zero one three four 4.2
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
162 chapter 6
]||(iss ).c
How does this crossword puzzle help you learn
1avaI well, all of the words are 1ava related
(except one red herring).
Hint: when in doubt, remember ArrayList.
Down
2. where the 1ava action is.
3. Addressable unit
4. 2nd smallest
5. Practional default
8. Library's grandest
l0. Must be low density
ll. He's in there somewhere
l5. As if
l6. dearth method
l8. what shopping and arrays have in common
20. Library acronym
2l. what goes around
l7
24
l2
8
2l
l6
ll
l9
22
l8
l3
l0
l5
2
23
9
3 l
6
l4
5
4
20
Across
l. | can't behave
6. Or, in the courtroom
7. where it's at baby
9. A fork's origin
l2. Grow an ArrayList
l3. wholly massive
l4. value copy
l6. Not an ob|ect
l7. An array on steroids
l9. Lxtent
2l. l9's counterpart
22. Spanish geek snacks (Note: This has
nothing to do with 1ava.)
23. Por lazy ngers
24. where packages roam
7
More Hints:
A c r o s s D o w n
l . 8 v a r i e t i e s 2 . w h a t ' s o v e r r i d a b l e I
7 . T h i n k A r r a y L i s t 3 . T h i n k A r r a y L i s t
l 6 . C o m m o n p r i m i t i v e 4 . & l 0 . P r i m i t i v e
2 l . A r r a y ' s e x t e n t l 6 . T h i n k A r r a y L i s t
2 2 . N o t a b o u t 1 a v a - S p a n i s h a p p e t i z e r s l 8 . H e ' s m a k i n g a _ _ _ _ _ _
puzzIe: crossword
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
get to know the Java API
you are here 163
File Edit Window Help Dance
% java ArrayListMagnet
zero one two three
zero one three four
zero one three four 4.2
zero one three four 4.2
]e;ejze o|ajoz
if (a.contains(three)) {
a.add(four);
}
import java.util.*;
public class ArrayListMagnet {
ArrayList<String> a = new ArrayList<String>();
public static void main (String[] args) {
a.add(0,zero);
a.add(1,one);
a.add(2,two);
a.add(3,three);
printAL(a);
a.remove(2);
if (a.indexOf(four) != 4) {
a.add(4, 4.2);
}
if (a.contains(two)) {
a.add(2.2);
}
public static void printAL(ArrayList<String> al) {
for (String element : al) {
System.out.print(element + );
}
System.out.println( );
}
}
}
printAL(a);
printAL(a);
printAL(a);
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
164 chapter 6
l7
24
l2
8
2l
l6
ll
l9
22
l8
l3
l0
l5
2
23
9
3 l
6
l4
5
4
20
7
| | M | 1 | / !
l ! | +
6 B ) ! c 1 | N l ! x 6 |
c + M
B | 6 | | ! 1 c
| A l l | 6 N 6 6
6 ! 1 c 6 1 N
r / A | N 1
A A / | | 1 | A
6 | _ ! |
A | ! N 6 1 + M N
| 6 c 1 A | A
| M | 6 1 A 1
| | | B A /
]||(iss
|nsacis
+,-+ :+ ,-+:.|
2. ___________________________________
3. ___________________________________
4. ___________________________________
5. ___________________________________
8. ___________________________________
l0. ___________________________________
ll. ___________________________________
l5. ___________________________________
l6. ___________________________________
l8. ___________________________________
20. ___________________________________
2l. ___________________________________
l. ___________________________________
6. ___________________________________
7. ___________________________________
9. ___________________________________
l2. ___________________________________
l3. ___________________________________
l4. ___________________________________
l6. ___________________________________
l7. ___________________________________
l9. ___________________________________
2l. ___________________________________
22. ___________________________________
23. ___________________________________
24. ___________________________________
write your OwN set of clues! Look at each word, and try to
write your own clues. Try making them easier, or harder, or
more technical than the ones we have.
puzzIe answers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
this is a new chapter 165
7 inheritance and poIymorphism
PIan your programs with the future in mind. |f there were a way to write
1ava code such that you could take more vacations, how much would it be worth to youI what
if you could write code that someone could extend, I And if you could write code
that was flexible, for those pesky last-minute spec changes, would that be something you're
interested inI Then this is your lucky day. Por |ust three easy payments of 60 minutes time, you
can have all this. when you get on the Polymorphism Plan, you'll learn the 5 steps to better class
design, the 3 tricks to polymorphism, the 8 ways to make flexible code, and if you act nowa
bonus lesson on the 4 tips for exploiting inheritance. Don't delay, an offer this good will give
you the design freedom and programming flexibility you deserve. |t's quick, it's easy, and it's
available now. Start today, and we'll throw in an extra level of abstraction!
Better Living in
Ob]ectville
We were underpoid,
overworked coders 'fiII we
fried fhe PoIymorphism PIon. 8uf
fhonks fo fhe PIon, our fufure is
brighf. Yours con be fool
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
166 chapter 7
0hz| r Wzrs Kcv|s| !c4...
Remember woy boch in chopter 2, when Lorry )proceduroI guy;
ond Brod )OO guy; were vying [or the Aeron choir Let`s Iooh ot
o [ew pieces o[ thot story to review the bosics o[ inheritonce.
LARRY: You`vc goi uulicaicu couc! Thc ioiaic ioccuuic
is in all loui Shac ihings. Ii`s a siuiu ucsign. You havc io
mainiain loui uillcicni ioiaic mcihous". How can ihai
cvci lc goou.
BRAD: Oh, I gucss you uiun`i scc ihc hnal ucsign. Ici mc
show you how OO inhcritancc woiIs, Iaiiy.
Ihcyrc 8hzpcs, zn4 !hcy z| | re!z!c zn4
p|zy8een4. 8e | z|s!rzr!c4 ee! !hc
remmen fcz!ercs zn4 pe! !hcm |n!e z
ncw r|zss rz| |c4 8hzpc.
3|ape
rolale()
p|ay3ourd()
Tr|ar|e 3quare C|rc|e Aroeoa
3|ape
rolale()
p|ay3ourd()
sepcrr|zss
se|r|zsscs
Ihcn | ||nkc4 !hc e!hcr
feer shzpc r|zsscs !e
!hc ncw 8hzpc r|zss,
|n z rc|z!|ensh|p rz||c4
|nhcr| !znrc.
Tr|ar|e
rolale()
p|ay3ourd()
3quare
rolale()
p|ay3ourd()
C|rc|e
rolale()
p|ay3ourd()
| |eekc4 z! whz! z|| feer
r|zsscs hzvc |n remmen.
Aroeoa
rolale()
p|ay3ourd()
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
inheritance and poIymorphism
you are here 169
sepcrr|zss
0oclor
Wor|sAllosp|la|
lrealPal|erl ()
Adds ore reW
|rslarce var|ao|e
Adds ore reW rel|od
se|r|zsscs
0verr|des l|e |r|er|led
lrealPal|erl() rel|od
Adds ore reW rel|od
3ureor
lrealPal|erl ()
ra|elrc|s|or()
Far||y0oclor
ra|eslouseCa||s
|veAdv|ce ()
enc |ns!znrc vzr|z||c
enc mc!he4
+,-+ :+ ,-+:.|
loW rary |rslarce var|ao|es does
3ureor |ave?
loW rary |rslarce var|ao|es does
Far||y0oclor |ave?
loW rary rel|ods does 0oclor |ave?
loW rary rel|ods does 3ureor |ave?
loW rary rel|ods does Far||y0oclor
|ave?
Car a Far||y0oclor do lrealPal|erl()?
Car a Far||y0oclor do ra|elrc|s|or()?
public class Doctor {
boolean worksAtHospital;
void treatPatient() {
// perform a checkup
}
}
public class FamilyDoctor extends Doctor {
boolean makesHouseCalls;
void giveAdvice() {
// give homespun advice
}
}
public class Surgeon extends Doctor{
void treatPatient() {
// perform surgery
}
void makeIncision() {
// make incision (yikes!)
}
}
I inherifed my
procedures so I didn'f
bofher wifh medicoI schooI.
PeIox, fhis won'f hurf o bif.
(now where did I puf fhof
power sow...)
n |nhcr| !znrc crzmp|c:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
170 chapter 7
Whut do these si types huve in
common? This heIps you to ubstruct
out behuviors, {step Z}
How ure these types reIuted? This
heIps you to dehne the inheritunce
tree reIutionships {step 4-}
Ic!s 4cs|]n !hc |nhcr| !znrc !rcc fer
zn n|mz| s|me|z!|en pre]rzm
Imaginc you`ic asIcu io ucsign a simulaiion iogiam ihai
lcis ihc usci ihiow a lunch ol uillcicni animals inio an
cnviionmcni io scc whai hacns. Wc uon`i havc io couc ihc
ihing now, wc`ic mosily inicicsicu in ihc ucsign.
Wc`vc lccn givcn a lisi ol ol ihc animals ihai will lc
in ihc iogiam, lui noi all. Wc Inow ihai cach animal will
lc icicscnicu ly an ol|cci, anu ihai ihc ol|ccis will movc
aiounu in ihc cnviionmcni, uoing whaicvci ii is ihai cach
aiiiculai iyc is iogiammcu io uo.
And we wont other progrommers to be obIe to odd new
hinds o[ onimoIs to the progrom ot ony time.
Iiisi wc havc io hguic oui ihc common, alsiiaci
chaiaciciisiics ihai all animals havc, anu luilu ihosc
chaiaciciisiics inio a class ihai all animal classcs can cxicnu.
picture
food
hunger
boundaries
location
makeNoise()
eat()
sleep()
roam()
Wc havc hvc instonce voriobIes:
picture - ihc hlc namc icicscniing ihc ]PEG ol ihis animal
[ood - ihc iyc ol loou ihis animal cais. Righi now, ihcic
can lc only iwo valucs: oi .
hunger - an ini icicscniing ihc hungci lcvcl ol ihc animal.
Ii changcs uccnuing on whcn anu how much) ihc
animal cais.
boundories - valucs icicscniing ihc hcighi anu wiuih ol
ihc sacc` loi cxamlc, 640 x 4S0) ihai ihc animals will
ioam aiounu in.
Iocotion - ihc X anu Y cooiuinaics loi whcic ihc animal is
in ihc sacc.
Wc havc loui methods:
moheNoise ) - lchavioi loi whcn ihc animal is suoscu io
maIc noisc.
eot); - lchavioi loi whcn ihc animal cncounicis iis
iclciicu loou souicc, oi .
sIeep); - lchavioi loi whcn ihc animal is consiucicu aslcc.
room); - lchavioi loi whcn ihc animal is noi caiing oi
slccing iolally |usi wanuciing aiounu waiiing io lum
inio a loou souicc oi a lounuaiy).
0s|n] |nhcr| !znrc !e zve|4
4ep||rz!|n] re4c |n se|r|zsscs
size
picture
food
prey
Dog
size
picture
food
prey
WoIf
size
picture
food
prey
Cat
size
picture
food
prey
Tiger
size
picture
food
prey
Hippo
size
picture
food
prey
Lion
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
172 chapter 7
Assumc ihai wc all agicc on onc ihing: ihc insiancc
vaiiallcs will woiI loi nII Animal iycs. A lion will
havc his own valuc loi iciuic, loou wc`ic ihinIing
en), hungci, lounuaiics, anu locaiion. A hio
will havc uillcicni .nIue loi his insiancc vaiiallcs,
lui hc`ll siill havc ihc samc vaiiallcs ihai ihc oihci
Animal iycs havc. Samc wiih uog, iigci, anu so on.
Bui whai aloui beLn..o..
Wh|rh mc!he4s shee|4 wc evcrr|4c!
Docs a lion maIc ihc samc as a uog. Docs
a cai liIc a hio. Maylc in ,ou. vcision, lui
in ouis, caiing anu maIing noisc aic Animal-iyc-
sccihc. Wc can`i hguic oui how io couc ihosc
mcihous in such a way ihai ihcy`u woiI loi any
animal. OK, ihai`s noi iiuc. Wc coulu wiiic ihc
maIcNoisc) mcihou, loi cxamlc, so ihai all ii uocs
is lay a sounu hlc uchncu in an insiancc vaiiallc
loi ihai iyc, lui ihai`s noi vciy sccializcu. Somc
animals mighi maIc uillcicni noiscs
loi uillcicni siiuaiions liIc onc
loi caiing, anu anoihci whcn
luming inio an cncmy, cic.)
So |usi as wiih ihc Amocla
ovciiiuing ihc Shac class ioiaic)
mcihou, io gci moic amocla-sccihc in
oihci woius, ur.que) lchavioi, wc`ll havc
io uo ihc samc loi oui Animal sulclasscs.
Pe z| | zn|mz|s cz! !hc szmc wzy!
Decide if o subcIoss
needs behoviors (mefhod
impIemenfofions) fhof ore specifc
fo fhof porficuIor subcIoss fype.
designing for inheritance
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
inheritance and poIymorphism
you are here 173
We Iook ut our cIusses und see
thut WoIf und Dog might huve some
behuvior in common und the sume goes
for Lion Tiger und Cut,
size
picture
food
prey
Dog
size
picture
food
prey
WoIf
size
picture
food
prey
Cat
size
picture
food
prey
Tiger
size
picture
food
prey
Hippo
size
picture
food
prey
Lion
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
+
-
-
-
| -
--
--
|
--,
1
--, .-
c
.l
-
--|
.-
:--
-l
- - :--
-
--
w-| .- l- .-- -l :.---:
-.]- l---': :---l- l.l
B61+ :|.::-: :--| -:-
picture
food
hunger
boundaries
location
makeNoise()
eat()
sleep()
roam()
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
174 chapter 7
Finish fhe cIoss hierorchy
FeIine
roam()
Canine
size
picture
food
prey
Lion
size
picture
food
prey
Tiger
size
picture
food
prey
Cat
size
picture
food
prey
WoIf
size
picture
food
prey
Dog
Since onimoIs oIreody hove on orgoni;ofionoI
hierorchy (fhe whoIe kingdom, genus, phyIum
fhing), we con use fhe IeveI fhof mokes fhe mosf
sense for cIoss design. We'II use fhe bioIogicoI
"fomiIies" fo orgoni;e fhe onimoIs by moking o
FeIine cIoss ond o Conine cIoss.
We decide thut Cunines couId use u common
roum{} method becuuse they tend to move in
pucks, We uIso see thut FeIines couId use u
common roum{} method becuuse they tend to
uvoid others of their own kind, We'II Iet Hippo
continue to use its inherited roum{} method
the generic one it gets from AnimuI,
So we're done with the design for now; we'II
come buck to it Iuter in the chupter,
size
picture
food
prey
Hippo
makeNoise()
eat()
roam()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
picture
food
hunger
boundaries
location
makeNoise()
eat()
sleep()
roam()
designing for inheritance
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
inheritance and poIymorphism
you are here 175
Wolf w = new Wolf();
w.makeNoise();
w.roam();
w.eat();
w.sleep();
Wh|rh mc!he4 |s rz||c4!
Thc Woll class has loui mcihous. Onc
inhciiicu liom Animal, onc inhciiicu liom
Caninc which is aciually an ovciiiuucn
vcision ol a mcihou in class Animal), anu
iwo ovciiiuucn in ihc Woll class. Whcn
you cicaic a Woll ol|cci anu assign ii io
a vaiiallc, you can usc ihc uoi ociaioi
on ihai iclcicncc vaiiallc io invoIc all
loui mcihous. Bui which ol ihosc
mcihous gcis callcu.
-.- . --- w-| --:l
:.||: l- --:-- - w-|
:.||: l- --:-- - c.---
:.||: l- --:-- - w-|
:.||: l- --:-- - A--.|
size
picture
food
prey
WoIf
Canine
roam()
makeNoise()
eat()
makeNoise()
eat()
sleep()
roam()
Whcn you call a mcihou on an ol|cci
iclcicncc, you`ic calling ihc mosi sccihc
vcision ol ihc mcihou loi ihai ol|cci iyc.
In oihci woius, the Iowest one wins:
Iowcsi" mcaning lowcsi on ihc
inhciiiancc iicc. Caninc is lowci ihan
Animal, anu Woll is lowci ihan Caninc,
so invoIing a mcihou on a iclcicncc
io a Woll ol|cci mcans ihc ]VM siaiis
looIing hisi in ihc Woll class. Il ihc ]VM
uocsn`i hnu a vcision ol ihc mcihou in
ihc Woll class, ii siaiis walIing lacI u
ihc inhciiiancc hiciaichy uniil ii hnus a
maich.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
176 chapter 7
0raW ar |r|er|larce d|arar |ere.
practice designing an inheritance tree
(-,- a,- |
oa|| qa--(:|-
You said that the 1VM starts
waIking up the inheritance tree,
starting at the cIass type you invoked
the method on (Iike the WoIf exampIe
on the previous page). ut what
happens if the 1VM doesn't ever nd
a match!
DecIore o reference
voriobIe
Dog
Creofe on objecf
Dog myDog = new Dog();
The 3 steps of ob]ect
declaration and assignment
1
2
3
Dog objecf
Dog myDog = new Dog();
Assigns the new Dog to the refer-
ence variable myDog. |n other words,
regrnm rhe remere cenrrel.
D
o
g
o
bj
e
c
f
1-:- l-- .-- l- :.-- l]- 1- ------:-
.-.|- l]- : -:|.-- .: l-, .- l- --:l
: :--.l- .: --- l-|`
But with polymorphism, the
reference and the ob]ect can
be different.
Animal myDog = new Dog();
AnimoI
D
o
g
o
bj
e
c
f
1-:- l-- .-- N61 l- :.-- l]- 1-
------:- .-.|- l]- : -:|.-- .: A--.|,
-l l- --:l : :--.l- .: --- l-|`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
186 chapter 7
With polymorphism, the reference
type can be a superclass of the
actual ob]ect type.
uh... nope.
SfiII nof geffin' if.
OK, OK maybe an example will help.
poIymorphism in action
Animal[] animals = new Animal[5];
animals [0] = new Dog();
animals [1] = new Cat();
animals [2] = new Wolf();
animals [3] = new Hippo();
animals [4] = new Lion();
for (int i = 0; i < animals.length; i++) {
animals[i].eat();
animals[i].roam();
}
l
-:|.-- .- .--.] - l]- A--.| |- -l-- ---:,
.- .--.] l.l -|| -| --:l: - l]- A--.|
B-l |-- -.l ]-- -l l- - ]-- :.- -l AN/
:-:|.:: - A--.| - l- A--.| .--.]'
A- ---': l- -:l -|]---: .-l |l-
-.:-- 'l-- -- l- --|- -.-|-`, ]--
-l l- |-- l--- l- .--.] .- :.|| ---
- l- A--.|~:|.:: --l-:, .- ---]
--:l --: l- -l l-'
w-- '' : o, . l- : .l -- o - l- .--.], :-
]-- -l l- l-': -.l|` --l- w-- '' : |, ]--
-l l- c.l': -.l|` --l-
.-- -l --.-|`
Whcn you ucclaic a iclcicncc vaiiallc,
any ol|cci ihai asscs ihc IS-A icsi loi ihc
ucclaicu iyc ol ihc iclcicncc vaiiallc
can lc assigncu io ihai iclcicncc. In
oihci woius, anyihing ihai e:erJ ihc
ucclaicu iclcicncc vaiiallc iyc can
lc n.reJ io ihc iclcicncc
vaiiallc. This Iets you do
things Iihe mohe poIymorphic
orroys.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
inheritance and poIymorphism
you are here 187
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
194 chapter 7
Powboat
Sailboat
8oat
subclasses
int length
int bl
extends
stroke natasha
Testboats
drift
return
int len
public
int b2
private
hoist sail
continue
int b2
int b3
break
length
bl
b2
b3
len
move
rowThe8oat
setLength
getLength
String
int
void
static
our is to take code snippets from the pool and place them into
the blank lines in the code. ou may use the same snippet more
than once, and you might not need to use all the snippets. our
is to make a set of classes that will compile and run together
as a program. Don't be fooled - this one's harder than it looks.
public class Rowboat ________ ________ {
public ___________ rowTheBoat{| {
System.out.print{"stroke natasha"|,
}
}
public class ________ {
private int __________ ,
_______ void _________ { ______ | {
length = len,
}
public int getLength{| {
________ _________ ,
}
public ___________ move{| {
System.out.print{"___________"|,
}
}
public class TestBoats {
______ ______ _______ main{String args|{
_________ bl = new Boat{|,
Sailboat b2 = new __________{|,
Rowboat ________ = new Rowboat{|,
b2.setLength{32|,
bl.__________{|,
b3.__________{|,
_______.move{|,
}
}
public class __________ ________ Boat {
public _______ _________{| {
System.out.print{"___________"|,
}
}
drift drift hoist sail
puzzIe: PooI PuzzIe
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
inheritance and poIymorphism
you are here 195
re4c
rzn4|4z!cs:
ee!pe!:
b.ml{|,
c.m2{|,
a.m3{|,
c.ml{|,
c.m2{|,
c.m3{|,
a.ml{|,
b.m2{|,
c.m3{|,
a2.ml{|,
a2.m2{|,
a2.m3{|,
A's ml, A's m2, C's m3, 6
B's ml, A's m2, A's m3,
A's ml, B's m2, A's m3,
B's ml, A's m2, C's m3, l3
B's ml, C's m2, A's m3,
B's ml, A's m2, C's m3, 6
A's ml, A's m2, C's m3, l3
}
}
}
Sef I wiII work.
Set 2 will not compile because of Vampire's return
type (int).
The Vampire's frighten() method (B) is not a legal
override OR overload of Monster's frighten() method.
Changing ONLY the return type is not enough
to make a valid overload, and since an int is not
compatible with a boolean, the method is not a valid
override. (Remember, if you change ONLY the return
type, it must be to a return type that is compatible
with the superclass version's return type, and then it's
an over.
Sets 3 and 4 will compile, but produce:
arrrgh
breath re
arrrgh
Remember, class Vampire did not over class
Monster's frighten() method. (The frighten() method
in Vampire's set 4 takes o byfe, nof on inf.)
] ge [omgj|e;
d
g
]e;ejze
o|ajoz
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
196 chapter 7
public class Rowboat exfends 8oof {
public void rowTheBoat{| {
System.out.print{"stroke natasha"|,
}
}
public class 8oof {
private int Iengfh ,
pubIic void sefLengfh { inf Ien | {
length = len,
}
public int getLength{| {
refurn Iengfh ,
}
public void move{| {
System.out.print{"driff "|,
}
}
public class TestBoats {
pubIic sfofic void main{String args|{
8oof bl = new Boat{|,
Sailboat b2 = new SoiIboof{|,
Rowboat b3 = new Rowboat{|,
b2.setLength{32|,
bl.move{|,
b3.move{|,
bZ.move{|,
}
}
public class SoiIboof exfends Boat {
public void move{| {
System.out.print{"hoisf soiI "|,
}
}
drift drift hoist sail
puzzIe answers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
this is a new chapter 197
8 interfaces and abstract cIasses
Inheritance is just the beginning. To exploit polymorphism, we need interfaces
(and not the GU| kind). we need to go beyond simple inheritance to a level of flexibility and
extensibility you can get only by designing and coding to interface specifications. Some of the
coolest parts of 1ava wouldn't even be possible without interfaces, so even if you don't design
with them yourself, you still have to use them. 8ut you'll to design with them. ou'll
to design with them. Yeull wenJer hew yeu ever liveJ wirheur rhem. what's an interfaceI |t's
a l00% abstract class. what's an abstract classI |t's a class that can't be instantiated. what's that
good forI ou'll see in |ust a few moments. 8ut if you think about the end of the last chapter,
and how we used polymorphic arguments so that a single vet method could take Animal
subclasses of all types, well, that was |ust scratching the surface. |nterfaces are the ely in
polymorphism. The nb in abstract. The cnIIeine in 1ava.
8erious Polymorphism
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
198 chapter 8
FeIine
roam()
Canine
size
picture
food
prey
Lion
size
picture
food
prey
Tiger
size
picture
food
prey
Cat
size
picture
food
prey
WoIf
size
picture
food
prey
Dog
size
picture
food
prey
Hippo
makeNoise()
eat()
roam()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
makeNoise()
eat()
picture
food
hunger
boundaries
location
makeNoise()
eat()
sleep()
roam()
designing with inheritance
P|4 wc fer]c! z|ee! semc!h|n]
whcn wc 4cs|]nc4 !h|s!
Thc class siiuciuic isn`i ioo lau. Wc`vc ucsigncu
ii so ihai uulicaic couc is Ici io a minimum,
anu wc`vc ovciiiuucn ihc mcihous ihai wc ihinI
shoulu havc sulclass-sccihc imlcmcniaiions.
Wc`vc mauc ii nicc anu ucxillc liom a
olymoihic ciscciivc, lccausc wc can ucsign
Animal-using iogiams wiih Animal aigumcnis
anu aiiay ucclaiaiions), so ihai any Animal
suliyc-incIuding those we never imogined ot the
time we wrote our code-can lc asscu in anu uscu
ai iuniimc. Wc`vc ui ihc common ioiocol loi
all Animals ihc loui mcihous ihai wc wani ihc
woilu io Inow all Animals havc) in ihc Animal
suciclass, anu wc`ic icauy io siaii maIing ncw
Iions anu Tigcis anu Hios.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 199
Wolf aWolf = new Wolf();
We know we can say:
A w-| ------:- l- .
w-| --:l WoIf
eWell
W
o
If
obj
e
c
f
1-:- l-- .-- l- :.-- l]-
Animal aHippo = new Hippo();
And we know we can say:
A--.| ------:- l-
. +- --:l
AnimoI
ehijje
H
i
p
p
o
obj
e
c
f
1-:- l-- .-- N61 l- :.-- l]-
Animal anim = new Animal();
But here's where it gets weird:
A--.| ------:- l-
.- A--.| --:l
AnimoI
erim
A
n
i
m
oI ob
j
e
c
f
1-:- l-- .-- l- :.-- l]-, -l
-.l l- -: --: .- A--.| --:l |-- |-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
200 chapter 8
,ezy je(,
What does a new Animal{} ob]ect
look like?
when objects go bad
Ii maIcs scnsc io cicaic a Woll ol|cci oi a Hio
ol|cci oi a Tigci ol|cci, lui whai cxacily . an
Animal ol|cci. Whai shac is ii. Whai coloi, sizc,
numlci ol lcgs...
Tiying io cicaic an ol|cci ol iyc Animal is liIc a
nightmarc Star Trck transportcr accidcnt. Thc
onc whcic somcwhcic in ihc lcam-mc--u ioccss
somcihing lau hacncu io ihc lullci.
Bui how uo wc ucal wiih ihis. Wc reeJ an Animal
class, loi inhciiiancc anu olymoihism. Bui wc
wani iogiammcis io insianiiaic only ihc lcss
alsiiaci ubIne ol class Animal, noi Animal iiscll.
Wc wani Tigci ol|ccis anu Iion ol|ccis, not AnimoI
objects.
Ioiiunaicly, ihcic`s a simlc way io icvcni a class
liom cvci lcing insianiiaicu. In oihci woius, io sio
anyonc liom saying new" on ihai iyc. By maiIing
ihc class as abstract, ihc comilci will sio any
couc, anywhcic, liom cvci cicaiing an insiancc ol
ihai iyc.
You can siill usc ihai alsiiaci iyc as a iclcicncc iyc.
In laci,ihai`s a lig aii ol why you havc ihai alsiiaci
class in ihc hisi lacc io usc ii as a olymoihic
aigumcni oi iciuin iyc, oi io maIc a olymoihic
aiiay).
Whcn you`ic ucsigning youi class inhciiiancc
siiuciuic, you havc io ucciuc which classcs aic
nb.n anu which aic or.ee. Concicic classcs aic
ihosc ihai aic sccihc cnough io lc insianiiaicu. A
or.ee class |usi mcans ihai ii`s OK io maIc ol|ccis
ol ihai iyc.
MaIing a class alsiiaci is casy-ui ihc Icywoiu
abstract lcloic ihc class ucclaiaiion:
abstract class Canine extends Animal {
public void roam() { }
}
What are the instance variable values?
8ome classes ]ust should not be
instantiatedl
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 201
Ihc remp||cr wen! |c! yee |ns!zn!|z!c
zn z|s!rzr! r|zss
An alsiiaci class mcans ihai nolouy can cvci maIc a ncw
insiancc ol ihai class. You can siill usc ihai alsiiaci class as a
ucclaicu iclcicncc iyc, loi ihc uiosc ol olymoihism, lui
you uon`i havc io woiiy aloui somclouy maIing ol|ccis ol ihai
iyc. Thc comilci un.nree ii.
abstract public class Canine extends Animal
{
public void roam() { }
}
public class MakeCanine {
public void go() {
Canine c;
c = new Dog();
c = new Canine();
c.roam();
}
}
File Edit Window Help BeamMeUp
% javac MakeCanine.java
MakeCanine.java:5: Canine is abstract;
cannot be instantiated
c = new Canine();
^
1 error
:|.:: c.--- : -.-- .:l-.:l,
:- l- :--|-- -|| N61
|-l ]-- - l:
An abstract class has virtually* no use, no value, no
purpose in life, unless it is extended.
With an abstract class, the guys doing the work at runtime
are instances of a subclass of your abstract class.
1
: : 6r, -:.-:- ]-- :.- .|-.]: .::-
. :-:|.:: --:l l- . :---:|.:: ------:-,
--- l- :---:|.:: : .:l-.:l
1--- : .- -:-l-- l- l:-.- .:l-.:l :|.:: :.-
.- :l.l: -----: |:-- :.l-- |o`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
202 chapter 8
|s!rzr! vs. 0enrrc!c
A class ihai`s noi alsiiaci is callcu
a or.ee class. In ihc Animal
inhciiiancc iicc, il wc maIc
Animal, Caninc, anu Iclinc
alsiiaci, ihai lcavcs Hio, Woll,
Dog, Tigci, Iion, anu Cai as ihc
concicic sulclasscs.
Ili ihiough ihc ]ava API anu
you`ll hnu a loi ol alsiiaci classcs,
csccially in ihc GUI liliaiy. Whai
uocs a GUI Comoncni looI
liIc. Thc Comoncni class is ihc
suciclass ol GUI-iclaicu classcs
loi ihings liIc luiions, icxi aicas,
sciolllais, uialog loxcs, you namc
ii. You uon`i maIc an insiancc ol
a gcnciic Coorer anu ui ii on
ihc sciccn, you maIc a ]Buiion. In
oihci woius, you insianiiaic only a
or.ee ubIn ol Comoncni, lui
ncvci Comoncni iiscll.
Tiger
Animal
Canine
.:l-.:l
.:l-.:l
.:l-.:l
Hippo
:--:--l-
Dog
WoIf
:--:--l-
Cat
Lion
:--:--l-
Hmmmm... do I
feeI Iike red or
whife fonighf7
Hmmmm... fhe ComeIof
Vineyords I997 Pinof
Moir wos o preffy
decenf yeor...
How do you know when a class should be
abstractI wine is probably abstract. 8ut what
about ReJ and whireI Again probably abstract
(for some of us, anyway). 8ut at what point in the
hierarchy do things become concreteI
Do you make PinerNeir concrete, or is it abstract
tooI |t looks like the Camelot vineyards l997
Pinot Noir is probably concrete no matter what.
8ut how do you know for sureI
Look at the Animal inheritance tree above. Do the
choices we've made for which classes are abstract
and which are concrete seem appropriateI
would you change anything about the Animal
inheritance tree (other than adding more Animals,
of course)I
abstract or concrete?
:--:--l-
:--:--l-
abstract and concrete cIasses
FeIine
:--:--l-
WWkm
Qw&W
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
interfaces and poIymorphism
you are here 203
|s!rzr! mc!he4s
Bcsiucs classcs, you can maiI eLoJ alsiiaci, ioo. An alsiiaci
class mcans ihc class musi lc e:erJeJ, an alsiiaci mcihou mcans
ihc mcihou musi lc o.e...JJer. You mighi ucciuc ihai somc oi all)
lchaviois in an alsiiaci class uon`i maIc any scnsc unlcss ihcy`ic
imlcmcnicu ly a moic sccihc sulclass. In oihci woius, you can`i
ihinI ol any gcnciic mcihou imlcmcniaiion ihai coulu ossilly lc
usclul loi sulclasscs. Whai woulu a gcnciic en() mcihou looI liIc.
An abstract method has no bodyl
Bccausc you`vc alicauy ucciucu ihcic isn`i any couc ihai woulu maIc
scnsc in ihc alsiiaci mcihou, you won`i ui in a mcihou louy. So no
cuily liaccs- |usi cnu ihc ucclaiaiion wiih a scmicolon.
public abstract void eat();
N- --l- -]'
!- l -l . :--:-|--
f you declare an abstract method, you MU8T
mark the class abstract as well. You can't have
an abstract method in a non-abstract class.
Il you ui cvcn a singlc alsiiaci mcihou in a class, you havc io
maIc ihc class alsiiaci. Bui you nr mix loih alsiiaci anu non-
alsiiaci mcihous in ihc alsiiaci class.
What is the of an abstract method! I thought
the whoIe point of an abstract cIass was to have common
code that couId be inherited by subcIasses.
|nheritable method implementations (in other words,
methods with actual ooJ|es) are A Good Thing to put in a
superclass. when |t moles sense. And in an abstract class, it
often Joesnt make sense, because you can't come up with
any generic code that subclasses would find useful. The
point of an abstract method is that even though you haven't
put in any actual method code, you've still defined part of
the totocol for a group of subtypes (subclasses).
Which is good because...
Polymorphism! Pemember, what you want is the
ability to use a superclass type (often abstract) as a method
argument, return type, or array type. That way, you get to
add new subtypes (like a new Animal subclass) to your
program without having to rewrite (or add) new methods
to deal with those new types. |magine how you'd have to
change the vet class, if it didn't use Animal as its argument
type for methods. ou'd have to have a separate method
for every single Animal subclass! One that takes a Lion, one
that takes a wolf, one that takes a... you get the idea. So with
an abstract method, you're saying, "All subtypes of this type
have TH|S method. for the benefit of polymorphism.
(-,- a,- |
oa|| qa--(:|-
If reoIIy sucks fo
be on obsfrocf mefhod.
You don'f hove o body.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
204 chapter 8
you must impIement abstract methods
Yee M08I |mp|cmcn! z|| z|s!rzr! mc!he4s
Alsiiaci mcihous uon`i havc a louy, ihcy cxisi solcly loi olymoihism. Thai
mcans ihc hisi concicic class in ihc inhciiiancc iicc musi imlcmcni nII alsiiaci
mcihous.
You can, howcvci, ass ihc lucI ly lcing alsiiaci youiscll. Il loih Animal anu
Caninc aic alsiiaci, loi cxamlc, anu loih havc alsiiaci mcihous, class Caninc
uocs noi havc io imlcmcni ihc alsiiaci mcihous liom Animal. Bui as soon as wc
gci io ihc hisi concicic sulclass, liIc Dog, ihai sulclass musi imlcmcni nII ol ihc
alsiiaci mcihous liom loih Animal anu Caninc.
Bui icmcmlci ihai an alsiiaci class can havc loih alsiiaci anu ror-alsiiaci
mcihous, so Caninc, loi cxamlc, coulu imlcmcni an alsiiaci mcihou liom
Animal, so ihai Dog uiun`i havc io. Bui il Caninc says noihing aloui ihc alsiiaci
mcihous liom Animal, Dog has io imlcmcni all ol Animal`s alsiiaci mcihous.
mplementing an abstract
method is ]ust like
overriding a method.
Whcn wc say you musi imlcmcni ihc alsiiaci mcihou", ihai mcans you u
.o..Je n boJ,. Thai mcans you musi cicaic a non-alsiiaci mcihou in youi class
wiih ihc samc mcihou signaiuic namc anu aigumcnis) anu a iciuin iyc ihai is
comaiillc wiih ihc ucclaicu iciuin iyc ol ihc alsiiaci mcihou. Whai you ui .r
ihai mcihou is u io you. All ]ava caics aloui is ihai ihc mcihou is Le.e, in youi
concicic sulclass.
I hove wonderfuI news,
mofher. Joe fnoIIy impIemenfed
oII his obsfrocf mefhodsl Mow
everyfhing is working jusf fhe
woy we pIonned...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 205
+,-+ :+ ,-+:.|
Let's put all this abstract rhetoric into some concrete use. |n the middle
column we've listed some classes. our |ob is to imagine applications
where the listed class might be concrete, and applications where the listed
class might be abstract. we took a shot at the rst few to get you going.
Por example, class Tree would be abstract in a tree nursery program, where
differences between an Oak and an Aspen matter. 8ut in a golf simulation
program, Tree might be a concrete class (perhaps a subclass of Obstacle),
because the program doesn't care about or distinguish between different
types of trees. (There's no one right answer, it depends on your design.)
Concrete SampIe cIass Abstract
]e|f reersc s|me|z!|en Tree !rcc nerscry zpp||rz!|en
____________________ House zrrh| !cr! zpp||rz!|en
sz!c||| !c phe!e zpp||rz!|en Town _____________________
____________________ Pootball Player rezrh|n] zpp||rz!|en
____________________ Chair _____________________
____________________ Customer _____________________
____________________ Sales Order _____________________
____________________ 8ook _____________________
____________________ Store _____________________
____________________ Supplier _____________________
____________________ Golf Club _____________________
____________________ Carburetor _____________________
____________________ Oven _____________________
Abstract vs. Concrete CIasses
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
206 chapter 8
poIymorphism exampIes
|e|ymerph|sm |n zr!|en
Ici`s say ihai wc wani io wiiic oui owr Iinu ol lisi class, onc ihai will holu
Dog ol|ccis, lui icicnu loi a momcni ihai wc uon`i Inow aloui ihc
AiiayIisi class. Ioi ihc hisi ass, wc`ll givc ii |usi an nJJ() mcihou. Wc`ll usc
a simlc Dog aiiay Dog ]|) io Icc ihc auucu Dog ol|ccis, anu givc ii a
lcngih ol . Whcn wc icach ihc limii ol Dog ol|ccis, you can siill call ihc
nJJ() mcihou lui ii won`i uo anyihing. Il wc`ic ro ai ihc limii, ihc nJJ()
mcihou uis ihc Dog in ihc aiiay ai ihc ncxi availallc inucx osiiion, ihcn
incicmcnis ihai ncxi availallc inucx ncxiInucx).
public class MyDogList {
private Dog [] dogs = new Dog[5];
private int nextIndex = 0;
public void add(Dog d) {
if (nextIndex < dogs.length) {
dogs[nextIndex] = d;
System.out.println(Dog added at + nextIndex);
nextIndex++;
}
}
}
Hy0ogL|st
0o[| dos
|rl rexllrdex
add(0o d)
c:- . |.- -| l- .--.]
-- l- ::---:
w-'|| -:-----l l: -.:
l-- . --- l- : .-
| --'-- --l .|--.] .l l- |-l
- l- -: .--.], . l- l-
.- --l . --::.-
-:-----l, l- - -: l-
--l -- l- -:-
Building our own Dog-specihc list
(Perhaps the worId's worst attempt at making our
own ArrayList kind of cIass, from scratch.)
1
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 207
public class MyAnimalList {
private Animal[] animals = new Animal[5];
private int nextIndex = 0;
public void add(Animal a) {
if (nextIndex < animals.length) {
animals[nextIndex] = a;
System.out.println(Animal added at + nextIndex);
nextIndex++;
}
}
}
HyAn|ma|L|st
An|ma|[j ar|ra|s
|rl rexllrdex
add(An|ma| a)
Building our own Animal-specihc list
2
0h-eh, new wc ncc4 !e kccp 0z!s, !ee.
Wc havc a lcw oiions hcic:
1) MaIc a scaiaic class, MyCaiIisi, io holu Cai ol|ccis. Piciiy clunIy.
2) MaIc a singlc class, DogAnuCaiIisi, ihai Iccs iwo uillcicni aiiays as insiancc
vaiiallcs anu has iwo uillcicni auu) mcihous: auuCaiCai c) anu auuDogDog
u). Anoihci clunIy soluiion.
S) MaIc hciciogcncous AnimalIisi class, ihai iaIcs nr, Iinu ol Animal sulclass
sincc wc Inow ihai il ihc scc changcu io auu Cais, soonci oi laici wc`ll havc
somc oLe. Iinu ol animal auucu as wcll). Wc liIc ihis oiion lcsi, so lci`s changc
oui class io maIc ii moic gcnciic, io iaIc Animals insicau ol |usi Dogs. Wc`vc
highlighicu ihc Icy changcs ihc logic is ihc samc, ol couisc, lui ihc iyc has
changcu liom Dog io Animal cvciywhcic in ihc couc.
public class AnimalTestDrive{
public static void main (String[] args) {
MyAnimalList list = new MyAnimalList();
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
l--'l .-: w-'-- --l -.- .
--- A--.| --:l. --'-- -.- .
--- .--.] --:l, - l]- A--.|
|------, ]-- :.---l -.- . ---
-:l.-:- - .- .:l-.:l l]-, -l
]-- cAN -.- .- .--.] --:l
-:|.-- l- +6|l l.l l]-`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
208 chapter 8
You Inow whcic ihis is hcauing. Wc wani io changc ihc
iyc ol ihc aiiay, along wiih ihc nJJ() mcihou aigumcni, io
somcihing nbo.e Animal. Somcihing cvcn o.e gcnciic, o.e
alsiiaci ihan Animal. Bui how can wc uo ii. Wc uon`i Ln.e a
suciclass loi Animal.
Thcn again, maylc wc uo...
Rcmcmlci ihosc mcihous ol AiiayIisi.
IooI how ihc icmovc, coniains, anu
inucxOl mcihou all usc an ol|cci ol iyc...
Object:
Every class in Java extends
class Ob]ect.
Class Ol|cci is ihc moihci ol all classcs, ii`s
ihc suciclass ol e.e.,L.r.
v
e
rsio
n
3
Whz! z|ee! nen-n|mz|s! Why ne! mzkc
z r|zss ]cncr|r cnee]h !e !zkc zny!h|n]!
M.-] - l- A--.]|:l --l-: -:- l-
-|l-.l- -|]---: l]-, 6-:l -:-
---] :|.:: - ).. : . :-:|.:: - 6-:l,
l-:- A--.]|:l --l-: :.- l.- .-]l-'
|N-l- .: - ).. -o, l- -l|` .- .|`
--l-: .:l-.||] |-- . |ll|- ----l
l.- l- ---: :--- ---, -l -- --- l:
: l- -.] l- l- .--l l w-'|| -l -l-
l- -|| :l--] . |ll|- |.l--`
the uItimate supercIass: Object
ArrayList
|1-:- .-- -:l . -- - l-
--l-: - A--.]|:ll---
.-- -.-] ----`
Evcn il you iaIc auvaniagc ol olymoihism,
you siill havc io cicaic a class wiih mcihous
ihai iaIc anu iciuin ,ou. olymoihic iyc.
Wiihoui a common suciclass loi cvciyihing
in ]ava, ihcic`u lc no way loi ihc ucvclocis
ol ]ava io cicaic classcs wiih mcihous ihai
coulu iaIc ,ou. cusiom iycs... ,e Le, re.e.
Irew nbou wLer Le, w.oe Le A..n,1. In.
So you wcic maIing sulclasscs ol class Ol|cci
liom ihc vciy lcginning anu you uiun`i cvcn
Inow ii. Every cIoss you write extends Object,
wiihoui youi cvci having io say ii. Bui you can
ihinI ol ii as ihough a class you wiiic looIs liIc
ihis:
public class Dog extends Object { }
Bui waii a minuic, Dog nI.enJ, cxicnus somcihing, Cnr.re.
Thai`s OK. Thc comilci will maIc Cnr.re cxicnu Ol|cci
insicau. Excci Cnr.re cxicnus Animal. No iollcm, ihcn ihc
comilci will |usi maIc Ar.nI cxicnu Ol|cci.
Any class that doesn't explicitly extend another
class, implicitly extends Ob]ect.
So, sincc Dog cxicnus Caninc, ii uocsn`i J..eI, cxicnu Ol|cci
alihough ii uocs cxicnu ii inuiiccily), anu ihc samc is iiuc
loi Caninc, lui Animal Joe uiiccily cxicnu Ol|cci.
Pemoves the ob|ect at the index parameter. Peturns
'true' if the element was in the list.
Peturns 'true' if there's a match for the ob|ect parameter.
Peturns 'true' if the list has no elements.
Peturns either the index of the ob|ect parameter, or -l.
Peturns the element at this position in the list.
Adds the element to the list (returns 'true').
booIean remove(Dbject eIem)
booIean contains(Dbject eIem)
booIean ismpty()
int indexDf(Dbject eIem)
Dbject get(int index)
booIean add(Dbject eIem)
// more
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 209
8e whz!s |n !h|s e| !rz-sepcr-mc]zr|zss 0|jcr!!
0bject
ooo|ear equa|s()
C|ass elC|ass()
|rl |as|Code()
3lr|r lo3lr|r()
Il you wcic ]ava, whai lchavioi woulu you wani
ol|cci io havc. Hmmmm... lci`s scc... how aloui a
mcihou ihai lcis you hnu oui il onc ol|cci is cqual
io anoihci ol|cci. Whai aloui a mcihou ihai can
icll you ihc aciual class iyc ol ihai ol|cci. Maylc a
mcihou ihai givcs you a hashcouc loi ihc ol|cci, so
you can usc ihc ol|cci in hashiallcs wc`ll ialI aloui
]ava`s hashiallcs in chaici 17 anu acnuix B).
Oh, hcic`s a goou onc-a mcihou ihai iinis oui a
Siiing mcssagc loi ihai ol|cci.
Anu whai uo you Inow. As il ly magic, class Ol|cci
uocs inuccu havc mcihous loi ihosc loui ihings.
Thai`s noi all, ihough, lui ihcsc aic ihc oncs wc
ically caic aloui.
)-:l 6M! - l- --l-:
- :|.:: 6-:l
Dog a = new Dog();
Cat c = new Cat();
if (a.equals(c)) {
System.out.println(true);
} else {
System.out.println(false);
}
equals{Ob]ect o} 1
Cat c = new Cat();
System.out.println(c.getClass());
getClass{} 2
File Edit Window Help Stop
% java TestObject
false
File Edit Window Help Faint
% java TestObject
class Cat
Cat c = new Cat();
System.out.println(c.hashCode());
hashCode{} 3
File Edit Window Help Drop
% java TestObject
8202111
Cat c = new Cat();
System.out.println(c.toString());
to8tring{} 4
File Edit Window Help LapsentoComa
% java TestObject
Cat@7d277f
|--l: --l . .::--
-- l- --:l |--
---, l- - l .: .
---- |l`
1-||: ]-- l-- --:l: .--
:--:--- '--.|' |--'|| l.|
.--l -.l '--.|' --.||]
--.-: - .-- B`
6-: ]-- .: l-
:|.:: l.l --:l -.:
-:l.-l.l- ---
|--l: --l . l-- --::.-
-l l- -.-- - l- :|.::
.- :--- -l-- ----- --
-.--|] :.-- .--l
Your6|asshere !--] :|.:: ]-- --l- ---l: .|| l-
--l-: - :|.:: 6-:l 1- :|.::-:
]--'- --ll-- ---l- --l-: ]--
-'l --- --- ]-- .
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
210 chapter 8
(-,- a,- |
oa|| qa--(:|-
Is cIass Dbject abstract!
No. well, not in the formal
1ava sense anyway. Ob|ect is a
non-abstract class because it's
got method implementation
code that all classes can inherit
and use out-of-the-box, without
having to override the methods.
7hen cnn you override
the methods in Dbject!
Some of them. 8ut some of
them are marked , which
means you can't override them.
ou're encouraged (strongly) to
override hashCode(), equals(),
and toString() in your own
classes, and you'll learn how to
do that a little later in the book.
8ut some of the methods, like
getClass(), do things that must
work in a specific, guaranteed
way.
If ArrayList methods are
generic enough to use Dbject,
then what does it mean to say
ArrayList<DotCom>! I thought
I was restricting the ArrayList to
hoId onIy DotCom objects!
ou wete restricting it.
Prior to 1ava 5.0, ArrayLists
couldn't be restricted. They
were all essentially what you
get in 1ava 5.0 today if you write
ArrayList<Ob|ect>. |n other
words, nn ArrnyLisr resrricreJ
re nnyrhing rhnrs nn 0bjecr,
which means ony ob|ect in 1ava,
instantiated from ony class type!
we'll cover the details of this new
<type> syntax later in the book.
Dk, back to cIass Dbject
being non-abstract (so I guess
that means it's concrete), HDW
can you Iet somebody make an
Dbject object! Isn't that just
as weird as making an AnimaI
object!
Good question! why is
it acceptable to make a new
Ob|ect instanceI 8ecause
sometimes you |ust want a
generic ob|ect to use as, well, as
an ob|ect. A l|htwe|ht ob|ect.
8y far, the most common use of
an instance of type Ob|ect is for
thread synchronization (which
you'll learn about in chapter l5).
Por now, |ust stick that on the
back burner and assume that
you will rarely make ob|ects of
type Ob|ect, even though you
con.
equa|s()
elC|ass()
|as|Code()
lo3lr|r()
1- --l- ]--'-- :.||- -- .
------:- Mc1 - - l- :|.:: -
l.l ------:- l]- l--:-'l -.ll--
-.l l- .:l-.| --:l :
o.hashCode();
1- -' ------:- -.: -:|.-- .: l]-
6-:l, :- ]-- :.- :.|| --l-: --|]
l-:- --l-: .-- - :|.:: 6-:l
o.b o.ba o.b
hoshCode( )
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
214 chapter 8
An ol|cci coniains e.e.,L.r ii inhciiis liom cach ol iis
suciclasscs. Thai mcans e.e., ol|cci-icgaiulcss ol iis
aciual class iyc-is nIo an insiancc ol class Ol|cci.Thai
mcans any ol|cci in ]ava can lc iicaicu noi |usi as a Dog,
Buiion, oi Snowloaiu, lui also as an Ol|cci. Whcn you
say new Snowboard(), you gci a singlc ol|cci on ihc
hca-a Snowloaiu ol|cci-lui ihai Snowloaiu wias
iiscll aiounu an innci coic icicscniing ihc Ol|cci
caiial O") oiiion ol iiscll.
0c! |n !eerh w| !h yeer |nncr 0|jcr!.
1--- : --|] 6N! --:l -- l- -. --- A ----.-
--:l B-l l :--l.-: -l l- ----.- :|.:: .-l: -
l:-| .- l- 6-:l :|.:: .-l: - l:-|
objects are Objects
0bject
equa|s()
elC|ass()
|as|Code()
lo3lr|r()
8nowboard
equa|s()
elC|ass()
|as|Code()
lo3lr|r()
lurr()
s|red()
elA|r()
|oseCorlro|()
----.- ---l: --l-:
--- :---:|.:: 6-:l, .-
.: --- ----
t
o
S
t
r
i
n
g
(
)
h
a
s
h
C
o
d
e
(
)
g
e
t
A
i
r
(
)
tu
r
n
(
)
s
h
r
e
d
(
)
e
q
u
a
l
s
(
)
g
etC
la
s
s
(
)
lo
se
C
o
n
t
r
o
l
(
)
Ob]ect
8nowboard
S
n
o
w
board
o
b
je
c
t
He freofs me Iike on
Objecf. 8uf I con do so
much more...if onIy he'd see
me for whof I reoIIy om.
A :-|- --:l
-- l- -.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 215
Snowboard s = new Snowboard();
Object o = s;
t
o
S
t
r
i
n
g
(
)
h
a
s
h
C
o
d
e
(
)
g
e
t
A
i
r
(
)
tu
r
n
(
)
s
h
r
e
d
(
)
e
q
u
a
l
s
(
)
g
etC
la
s
s
(
)
lo
se
C
o
n
t
r
o
l
(
)
Ob]ect
8nowboard
1- 6-:l ------:- :.- :-- --|] l-
6-:l .-l: - l- ----.- --:l
|l :.- .::-:: --|] l- --l-: - :|.::
6-:l |l .: ---- -ll--: l.- l-
----.- ----l- :--l--|
o
s
1- ----.- ----l- :--l--|
|------:-` .: ---- -ll--: l.-
.- 6-:l ----l- :--l--| 1-
----.- ----l- :.- :-- l- -||
----.---:: - l- ----.-
--:l |l :.- .::-:: .|| l- --l-:
- ----.-, -:|-- -l l-
---l- 6-:l --l-: .- l-
--l-: --- :|.:: ----.-
S
n
o
w
board
o
b
je
c
t
Il a iclcicncc is liIc a icmoic coniiol, ihc
icmoic coniiol iaIcs on moic anu moic luiions
as you movc uown ihc inhciiiancc iicc. A
icmoic coniiol iclcicncc) ol iyc Ol|cci has
only a lcw luiions-ihc luiions loi ihc cxoscu
mcihous ol class Ol|cci. Bui a icmoic coniiol
ol iyc Snowloaiu incluucs all ihc luiions liom
class Ol|cci, lus any ncw luiions loi ncw
mcihous) ol class Snowloaiu. Thc moic sccihc
ihc class, ihc moic luiions ii may havc.
Ol couisc ihai`s noi always iiuc, a sulclass mighi
noi auu any ncw mcihous, lui simly ovciiiuc
ihc mcihous ol iis suciclass. Thc Icy oini is
ihai cvcn il ihc obe is ol iyc Snowloaiu, an
Ol|cci .ee.ere io ihc Snowloaiu ol|cci can`i scc
ihc Snowloaiu-sccihc mcihous.
Polymorphism' means
many forms'.
You can treat a 8nowboard as a
8nowboard or as an Ob]ect.
When you put
an ob]ect in an
ArrayList<Ob]ect>, you
can treat it only as an
Ob]ect, regardless of
the type it was when
you put it in.
When you get a
reference from an
ArrayList<Ob]ect>, the
reference is always of
type Ob]ect.
That means you get an
Ob]ect remote control.
---- --l-: ---
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
216 chapter 8
Woif o minufe... whof good
is o Dog if if comes ouf of on
ArroyLisfObjecf ond if con'f do
ony Dog fhings7 There's goffo be o
woy fo gef fhe Dog bock fo o sfofe
of Dogness...
I hope if doesn'f hurf.
And whof's so wrong wifh
sfoying on Objecf7 OI, I con'f
fefch, sure, buf I con give you
o reoI nice hoshcode.
casting objects
Casting an ob]ect reference
back to its real type.
Objecf
Ii`s ically siill a Dog obe, lui il you wani io call
Dog-sccihc mcihous, you nccu a .ee.ere ucclaicu
as iyc Dog. Il you`ic u.e` ihc ol|cci is ically a
Dog, you can maIc a ncw Dog iclcicncc io ii ly
coying ihc Ol|cci iclcicncc, anu loicing ihai
coy io go inio a Dog iclcicncc vaiiallc, using a
casi Dog). You can usc ihc ncw Do iclcicncc io
call Do mcihous.
Object o = al.get(index);
Dog d = (Dog) o;
d.roam();
Objecf
D
o
g
ob
j
e
c
f
Dog
deo|l(douo|e arl)
cred|l(douo|e arl)
douo|e el8a|arce()
8o now you've seen how much Java
cares about the methods in the
class of the reference variable.
You can call a method on an ob]ect only if
the class of the reference variable has that
method.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
218 chapter 8
OK, icicnu you`ic a Dog. Youi Dog class
isn`i ihc orI, coniiaci ihai uchncs who you
aic. Rcmcmlci, you inhciii acccssillc which
usually mcans ubI.) mcihous liom all ol
youi suciclasscs.
Tiuc, youi Dog class uchncs a coniiaci.
Bui noi nII ol youi coniiaci.
Evcrything in class Conine is part oI your
contract.
Evcrything in class AnimoI is part oI your
contract.
Evcrything in class Object is part oI your
contract.
Accoiuing io ihc IS-A icsi, you n.e cach ol
ihosc ihings-Caninc, Animal, anu Ol|cci.
Bui whai il ihc cison who ucsigncu youi
class hau in minu ihc Animal simulaiion
iogiam, anu now hc wanis io usc you class
Dog) loi a Scicncc Iaii Tuioiial on Animal
ol|ccis.
Thai`s OK, you`ic iolally icusallc loi ihai.
Bui whai il laici hc wanis io usc you loi a
PciSho iogiam. You Jor` Ln.e nr, Pet
beLn..o.. A Pci nccus mcihous liIc beE..erJI,()
anu In,().
OK, now icicnu you`ic ihc Dog class
iogiammci. No iollcm, iighi. ]usi auu
somc moic mcihous io ihc Dog class. You
won`i lc licaIing anyonc clsc`s couc ly
nJJ.r mcihous, sincc you aicn`i iouching
ihc e:..r mcihous ihai somconc clsc`s couc
mighi lc calling on Dog ol|ccis.
Can you scc any uiawlacIs io ihai aioach
auuing Pci mcihous io ihc Dog class).
Whz! |f yee ncc4 !e rhzn]c
!hc ren!rzr!!
Think obouf whof YOU wouId do if YOU were
fhe Dog cIoss progrommer ond needed fo
modify fhe Dog so fhof if couId do Pef fhings,
foo. We know fhof simpIy odding new Pef be-
hoviors (mefhods) fo fhe Dog cIoss wiII work,
ond won'f breok onyone eIse's code.
8uf... fhis is o PefShop progrom. If hos more
fhon jusf Dogsl And whof if someone wonfs
fo use your Dog cIoss for o progrom fhof hos
wiId Dogs7 Whof do you fhink your opfions
mighf be, ond wifhouf worrying obouf how
Jovo hondIes fhings, jusf fry fo imogine how
you'd Iike fo soIve fhe probIem of modifying
some of your AnimoI cIosses fo incIude Pef
behoviors.
Sfop righf now ond fhink obouf if,
before you Iook ut the net puge where we
begin fo reveoI everyfhing.
(l|us rerder|r l|e W|o|e exerc|se corp|ele|y use|ess, rooo|r
you ol your 0re 8| C|arce lo ourr sore ora|r ca|or|es)
modifying a cIass tree
WWkm
Qw&W
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 219
On ihc ncxi lcw agcs, wc`ic going io walI ihiough
somc ossililiiics. Wc`ic noi yci woiiicu aloui
whcihci ]ava can aciually whai wc comc u wiih.
Wc`ll cioss ihai liiugc oncc wc havc a goou iuca ol
somc ol ihc iiaucolls.
Ic!s crp|erc semc 4cs|]n ep!|ens
fer rces|n] semc ef eer cr|s!|n]
r|zsscs |n z |c!8hep pre]rzm.
We foke fhe eosy pofh, ond puf pef
mefhods in cIoss AnimoI.
1
0p!|en enc
AII fhe AnimoIs wiII insfonfIy inherif
fhe pef behoviors. We won'f hove fo
fouch fhe exisfing AnimoI subcIosses
of oII, ond ony AnimoI subcIosses
creofed in fhe fufure wiII oIso gef fo
foke odvonfoge of inherifing fhose
mefhods. Thof woy, cIoss AnimoI con
be used os fhe poIymorphic fype in
ony progrom fhof wonfs fo freof fhe
AnimoIs os pefs
|res:
So... when wos fhe Iosf fime you
sow o Hippo of o pef shop7 Lion7
WoIf7 CouId be dongerous fo give
non-pefs pef mefhods.
AIso, we oImosf cerfoinIy WILL
hove fo fouch fhe pef cIosses
Iike Dog ond Cof, becouse (in
our house, onywoy) Dogs
ond Cofs fend fo impIe-
menf pef behoviors
VEPY differenfIy.
0ens:
Tiger
Canine
Hippo
Dog
WoIf
Cat
Lion
FeIine
-
l
.
|| l
-
-
l
-
-
l
:
-
-
-
-
-
-
-
-
-
-
-
l
.
-
:
-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
220 chapter 8
We sforf wifh Opfion One, puffing fhe pef mefhods
in cIoss AnimoI, buf we moke fhe mefhods obsfrocf,
forcing fhe AnimoI subcIosses fo override fhem.
2
0p!|en ! we
Thof wouId give us oII fhe beneffs of Opfion One, buf wifh-
ouf fhe drowbock of hoving non-pef AnimoIs running oround
wifh pef mefhods (Iike beFriendIy()). AII AnimoI cIosses
wouId hove fhe mefhod (becouse if's in cIoss AnimoI), buf
becouse if's obsfrocf fhe non-pef AnimoI cIosses won'f
inherif ony funcfionoIify. AII cIosses MUST override fhe
mefhods, buf fhey con moke fhe mefhods "do-nofhings".
|res:
8ecouse fhe pef mefhods in fhe AnimoI cIoss ore oII
obsfrocf, fhe concrefe AnimoI subcIosses ore forced fo
impIemenf oII of fhem. (Pemember, oII obsfrocf mefhods
MUST be impIemenfed by fhe frsf concrefe subcIoss
down fhe inherifonce free.) Whof o wosfe of fimel
You hove fo sif fhere ond fype in eoch ond every
pef mefhod info eoch ond every concrefe non-
pef cIoss, ond oII fufure subcIosses os weII.
And whiIe fhis does soIve fhe probIem of
non-pefs ocfuoIIy DOIM0 pef fhings
(os fhey wouId if fhey inherifed pef
funcfionoIify from cIoss AnimoI), fhe
confrocf is bod. Every non-pef
cIoss wouId be onnouncing fo fhe
worId fhof if, foo, hos fhose
pef mefhods, even fhough
fhe mefhods wouIdn'f
ocfuoIIy DO onyfhing
when coIIed.
This opprooch doesn'f
Iook good of oII. If jusf
seems wrong fo sfuff
everyfhing info cIoss AnimoI
fhof more fhon one AnimoI fype
mighf need, UMLESS if oppIies fo
ALL AnimoI subcIosses.
0ens:
Tiger
Canine
Hippo
Dog
WoIf
Cat
Lion
FeIine
-
l
.
|| l
-
-
l
-
-
l
:
-
-
-
-
,
-
l
-
l
-
-
-
|-
-
-
-
l
.
l
-
-
: M
.
-
.
||
-
l
-
-
l
: .
:l
-
.
:
l
Ask me fo be friendIy.
Mo, seriousIy... osk me.
I hove fhe mefhod.
modifying existing cIasses
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
interfaces and poIymorphism
you are here 221
Puf fhe pef mefhods OMLY in fhe
cIosses where fhey beIong.
3
0p!|en !hrcc
Mo more worries obouf Hippos greefing you of fhe
door or Iicking your foce. The mefhods ore where
fhey beIong, ond OMLY where fhey beIong. Dogs con
impIemenf fhe mefhods ond Cofs con impIemenf fhe
mefhods, buf nobody eIse hos fo know obouf fhem.
|res:
Two 8ig ProbIems wifh fhis opprooch. Firsf off, you'd
hove fo ogree fo o profocoI, ond oII progrommers of
pef AnimoI cIosses now ond in fhe fufure wouId hove
fo IMOW obouf fhe profocoI. 8y profocoI, we meon
fhe exocf mefhods fhof we've decided oII pefs shouId
hove. The pef confrocf wifhouf onyfhing fo bock if up.
8uf whof if one of fhe progrommers gefs if jusf o finy
bif wrong7 Like, o mefhod fokes o Sfring when if wos
supposed fo foke on inf7 Or fhey nomed if doFriendIy()
insfeod of beFriendIy()7 Since if isn'f in o confrocf,
fhe compiIer hos no woy fo check you fo see if you've
impIemenfed fhe mefhods correcfIy. Someone
couId eosiIy come oIong fo use fhe pef AnimoI
cIosses ond fnd fhof nof oII of fhem work
quife righf.
And second, you don'f gef fo use
poIymorphism for fhe pef mefhods.
Every cIoss fhof needs fo use
pef behoviors wouId hove fo
know obouf eoch ond every
cIossl In ofher words,
you con'f use AnimoI
os fhe poIymorphic
fype now, becouse fhe
compiIer won'f Ief you coII
o Pef mefhod on on AnimoI
reference (even if if's reoIIy o
Dog objecf) becouse cIoss AnimoI
doesn'f hove fhe mefhod.
0ens:
|-l l- -l --l-: 6N|/ - l-
A--.| :|.::-: l.l :.- - -l:,
-:l-. - - A--.|
Tiger
Canine
Hippo
Dog
WoIf
Cat
Lion
FeIine
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
222 chapter 8
8o what we REALLY need is:
A Way lo |ave pel oe|av|or |r just l|e pel c|asses
A Way lo uararlee l|al a|| pel c|asses |ave a|| ol l|e sare
rel|ods del|red (sare rare, sare arurerls, sare relurr
lypes, ro r|ss|r rel|ods, elc.), W|l|oul |av|r lo cross your
l|rers ard |ope a|| l|e prorarrers el |l r||l.
A Way lo la|e advarlae ol po|yrorp||sr so l|al a|| pels car |ave
l|e|r pel rel|ods ca||ed, W|l|oul |av|r lo use arurerls, relurr
lypes, ard arrays lor eac| ard every pel c|ass.
Tiger
Animal
Canine
Hippo
Dog
WoIf
Cat Lion
FeIine
Pet
t looks like we need TWO
superclasses at the top
w
-
-
.
-
.
-
-
-
.
:l
-
.
:
l
:-
-
-
:
|.
::
:
.
||-
|
-
l
,
.
-
-
l
.
||
l
-
l
-
-
l
:
c.l --- -l--:
--- -l A--.|
ANl
|-l, :- l -l:
l- --l-: - -l
l
-
l
-
-
:
-
l
|
-
l
.
-
A
-
-
.
|
1- ---~-l A--.|:
--'l .- .-] ---l-
|-l :l-
muItipIe inheritance?
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
interfaces and poIymorphism
you are here 223
t's called multiple inheritance
and it can be a Really Bad Thing.
Thof is, if if were possibIe fo do in Jovo.
8uf if isn'f, becouse muIfipIe inherifonce hos o probIem
known os The DeodIy Diomond of Deofh.
There's jusf one probIem wifh fhe "fwo supercIosses" opprooch...
60urner
ourr()
0V0urner
0|g|ta|Recorder
|rl |
ourr()
ourr()
6ombo0r|ve
cl
B
----- .- l
/l
B
----- -l
---l --- l
l.|-:----,
.- -l ----- l- ---|`
--l- B
-l ---l l- '
-:l.-:- .-.|-
Deadly Diamond of Death
|--|-- -l --|l|- ---l.-:-
w
: ---|` --l- ---: --- ]--
:.|| ---|` -- l- c---l
--
|-
.-- l.l l- ' -:l.-:-
.-.|- : -:-
] -l c
l
B
-----
.-
l
/
l
B
-----, -
l
----l
.|--: w
.l .--:
c
--
-l
--
---
: l- -:- -l .|--: -
'
A languagc ihai allows ihc Dcauly Diamonu ol Dcaih can lcau io
somc ugly comlcxiiics, lccausc you havc io havc sccial iulcs io
ucal wiih ihc oicniial amliguiiics. Anu cxiia iulcs mcans cxiia
woiI loi you loih in Ien.r.r ihosc iulcs anu waiching oui loi
ihosc sccial cascs". ]ava is suoscu io lc .Ie, wiih consisicni
iulcs ihai uon`i llow u unuci somc sccnaiios. So ]ava unliIc
C++) ioiccis you liom having io ihinI aloui ihc Dcauly Dia-
monu ol Dcaih. Bui ihai liings us lacI io ihc oiiginal iollcm!
How Jo we LnrJIe Le Ar.nI/Pe L.r:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
224 chapter 8
|n!crfzrc !e !hc rcsrec|
w|er you dor'l Warl a c|ass lo oe |rslarl|aled (|r ol|er Words, you dor'l
Warl aryore lo ra|e a reW oojecl ol l|al c|ass lype) rar| l|e c|ass W|l| l|e
abstract |eyWord.
ll a c|ass |as ever one aoslracl rel|od, l|e c|ass rusl oe rar|ed aoslracl.
Ar aoslracl rel|od |as ro oody, ard l|e dec|aral|or erds W|l| a ser|co|or (ro
cur|y oraces).
A|| aoslracl rel|ods rusl oe |rp|ererled |r l|e l|rsl corcrele suoc|ass |r l|e
|r|er|larce lree.
You car ca|| rel|ods or ar oojecl on|y |l l|e rel|ods are |r l|e c|ass (or |rlerlace)
used as l|e relerenoe var|ao|e lype, reard|ess ol l|e aclua| oojeor lype. 3o, a
relererce var|ao|e ol lype 0ojecl car oe used or|y lo ca|| rel|ods del|red |r c|ass
0ojecl, reard|ess ol l|e lype ol l|e oojecl lo W||c| l|e relererce relers.
A relererce var|ao|e ol lype 0ojecl car'l oe ass|red lo ary ol|er relererce lype
W|l|oul a oasr. A casl car oe used lo ass|r a relererce var|ao|e ol ore lype lo a
relererce var|ao|e ol a suolype, oul al rurl|re l|e casl W||| la|| |l l|e oojecl or l|e
|eap |s N0T ol a lype corpal|o|e W|l| l|e casl.
Exarp|e: Dog d = (Dog) x.getObject(aDog);
A|| oojecls core oul ol ar ArrayL|sl<0ojecl> as lype 0ojecl (rear|r, l|ey car oe
relererced or|y oy ar 0ojecl relererce var|ao|e, ur|ess you use a oasr).
Vu|l|p|e |r|er|larce |s rol a||oWed |r Java, oecause ol l|e proo|ers assoc|aled W|l|
l|e '0ead|y 0|arord ol 0eal|. T|al rears you car exlerd or|y ore c|ass (|.e. you
car |ave or|y ore |rred|ale superc|ass).
Ar |rlerlace |s |||e a 100 pure aoslracl c|ass. ll del|res on|y aoslracl rel|ods.
Creale ar |rlerlace us|r l|e interface |eyWord |rslead ol l|e Word class.
A c|ass l|al |rp|ererls ar |rlerlace musr |rp|ererl a|| l|e rel|ods ol l|e
|rlerlace, s|rce ell interfece methods ere imlicitly ublic end ebstrect.
To |rvo|e l|e superc|ass vers|or ol a rel|od lror a suoc|ass l|al's overr|dder l|e
rel|od, use l|e super |eyWord. Exarp|e: super.runReport();
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
232 chapter 8
public int iMethod( ) ,
public int iMethod } }
public int iMethod ( ) }
public int iMethod ( ) } }
class
extends
interface
implements
our is to take code snippets from the pool and
place them into the blank lines in the code and out-
put. ou may use the same snippet more than once,
and you won't need to use all the snippets. our
is to make a set of classes that will compile
and run and produce the output listed.
Note: ach snippet
from the pooI can be
used more than oncel
File Edit Window Help BeAfraid
%java ______________
5 class Acts
7 class Clowns
________Of76
Dutput
____________ Nose {
________________________
}
abstract class Picasso implements ______{
_________________________
return 7,
}
}
class _________ ________ __________ { }
class _________ ________ __________ {
___________________________
return 5,
}
}
public ___________ ________ extends Clowns {
public static void main{String args| {
____________________________
i0 = new __________
il = new __________
i2 = new __________
for{int x = 0, x < 3, x++| {
System.out.println{__________________
+ " " + _______.getClass{ | |,
}
}
}
Acts( ),
Nose( ),
Of76( ),
Clowns( ),
Picasso( ),
Acts
Nose
Of76
Clowns
Picasso
i
i( )
i(x)
i|x|
i.iMethod(x)
i(x).iMethod| |
i|x|.iMethod( )
i|x|.iMethod| |
Of76 | | i new Nose|3|,
Of76 | 3 | i,
Nose | | i new Nose( ),
Nose | | i new Nose|3|,
class
5 class
7 class
7 public class
inferfoce Nose {
pubIic inf iMefhod( ) ,
}
abstract class Picasso implements Mose {
pubIic inf iMefhod( ) {
return 7,
}
}
class CIowns exfends Picosso { }
class Acfs exfends Picosso {
pubIic inf iMefhod( ) {
return 5,
}
}
puzzIe soIution
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
this is a new chapter 235
9 constructors and garbage coIIection
Objects are born and objects die. ou're in charge of an ob|ect's lifecycle.
ou decide when and how to construct it. ou decide when to destroy it. Lxcept you don't
actually Jesttoy the ob|ect yourself, you simply ooonJon it. 8ut once it's abandoned, the
heartless Carbage CoIIector (gc) can vaporize it, reclaiming the memory that ob|ect was
using. |f you're gonna write 1ava, you're gonna create ob|ects. Sooner or later, you're gonna
have to let some of them go, or risk running out of PAM. |n this chapter we look at how ob|ects
are created, where they live while they're alive, and how to keep or abandon them efficiently.
That means we'll talk about the heap, the stack, scope, constructors, super constructors, null
references, and more. warning: this chapter contains material about ob|ect death that some
may find disturbing. 8est not to get too attached.
Life and Death
of an Ob]ect
...fhen he soid,
"I con'f feeI my Iegsl" ond
I soid "Joel Sfoy wifh me Joel"
8uf if wos... foo Iofe. The gorboge
coIIecfor come ond... he wos gone.
8esf objecf I ever hod.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
236 chapter 9
Ihc 8!zrk zn4 !hc Hczp: whcrc !h|n]s || vc
Bcloic wc can unucisianu whai ically hacns whcn
you cicaic an ol|cci, wc havc io sic lacI a lii. Wc
nccu io lcain moic aloui whcic cvciyihing livcs
anu loi how long) in ]ava. Thai mcans wc nccu io
lcain moic aloui ihc SiacI anu ihc Hca. In ]ava, wc
iogiammcis) caic aloui iwo aicas ol mcmoiy-ihc
onc whcic ol|ccis livc ihc hca), anu ihc onc
whcic mcihou invocaiions anu local vaiiallcs livc
ihc siacI). Whcn a ]VM siaiis u, ii gcis a chunI ol
mcmoiy liom ihc unucilying OS, anu uscs ii io iun
youi ]ava iogiam. How uL mcmoiy, anu whcihci
oi noi you can iwcaI ii, is uccnucni on which
vcision ol ihc ]VM anu on which lailoim) you`ic
iunning. Bui usually you wor` havc anyihing io say
aloui ii. Anu wiih goou iogiamming, you iolally
won`i caic moic on ihai a liiilc laici).
Wc Inow ihai all obe livc on ihc gailagc-collcciillc
hca, lui wc havcn`i yci looIcu ai whcic .n..nbIe
livc. Anu whcic a vaiiallc livcs uccnus on whai I.rJ
ol vaiiallc ii is. Anu ly Iinu", wc uon`i mcan ,e
i.c. iimiiivc oi ol|cci iclcicncc). Thc iwo I.rJ ol
vaiiallcs whosc livcs wc caic aloui now aic .rnre
vaiiallcs anu IonI vaiiallcs. Iocal vaiiallcs aic also
Inown as nI vaiiallcs, which is a lig cluc loi whcic
ihcy livc.
Ihc 8!zrk
where method invocations
and local variables live
-.-|`
-l-|`
-|`
8
u
f
fon o
b
j
e
c
f
D
u
c
k ob
j
e
c
f
S
n
o
w
b
oord
o
b
j
e
c
f
Ihc Hczp
.|:- ---
- .:
1
- 6
.-.-~
c
-||-:l
|- +
-.'
where ALL ob|ects live
nstance Variables Local Variables
Instance variabIes are decIared inside a clnss but ner
inside a method. They represent the "elds that each
individual ob|ect has (which can be lled with different
values for each instance of the class). |nstance variables
live inside the ob|ect they belong to.
public class Duck {
int size;
}
!--] l
-: .: . :--'
-:l.-:- .-.|-
LocaI variabIes are decIared inside a merheJ, incIuding
method parameters. They're temporary, and live only as
long as the method is on the stack (in other words, as long as
the method has not reached the closing curly brace).
public void foo(int x) {
int i = x + 3;
boolean b = true;
}
1
- .-.-
-l-- .-
l- .-.|-: .-
.-- .|| |-:.| .-.|-:
the stack and the heap
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 237
public void doStuff() {
boolean b = true;
go(4);
}
public void go(int x) {
int z = x + 24;
crazy();
// imagine more code here
}
public void crazy() {
char c = `a';
}
Mc!he4s zrc s!zrkc4
Whcn you call a mcihou, ihc mcihou lanus on
ihc io ol a call siacI. Thai ncw ihing ihai`s
aciually ushcu onio ihc siacI is ihc siacI
.ne, anu ii holus ihc siaic ol ihc mcihou
incluuing which linc ol couc is cxccuiing, anu
ihc valucs ol all local vaiiallcs.
Thc mcihou ai ihc o ol ihc siacI is always
ihc cuiicnily-iunning mcihou loi ihai siacI
loi now, assumc ihcic`s only onc siacI,lui in
chaici 14 wc`ll auu moic.) A mcihou siays on
ihc siacI uniil ihc mcihou hiis iis closing cuily
liacc which mcans ihc mcihou`s uonc). Il
mcihou oo() calls mcihou bn.(), mcihou bn.() is
siacIcu on io ol mcihou oo().
.-|`
--|`
:l
.:
-.-
-:
-ll-- - l- :l.:
l- - l- :l.:
|-:.| .-.|-:
|-:|--
.-.--l-- `
A coII sfock wifh fwo mefhods
1
Code from onofher
cIoss coIIs doStuff{},
ond doStuff{} goes
info o sfock frome
of fhe fop of fhe
sfock.The booIeon
voriobIe nomed 'b'
goes on fhe doStuff{}
sfock frome.
:
-l-|`
-|`
-l-|`
-
2
doStuff{} coIIs go{},
go{} is pushed on
fop of fhe sfock.
VoriobIes '' ond 'z'
ore in fhe go{} sfock
frome.
:-.-]|`
:
-l-|`
-|` -
-|`
-l-|`
-
3
go{} coIIs cruzy{},
cruzy{} is now on fhe
fop of fhe sfock,
wifh voriobIe 'c' in
fhe frome.
4
cruzy{} compIefes,
ond ifs sfock frome is
popped off fhe sfock.
Execufion goes bock
fo fhe go{} mefhod,
ond picks up of fhe
Iine foIIowing fhe coII
fo cruzy{}.
Thc couc on ihc lcli is a snici wc uon`i caic whai ihc icsi ol ihc
class looIs liIc) wiih ihicc mcihous. Thc hisi mcihou JoSu()) calls
ihc scconu mcihou o()), anu ihc scconu mcihou calls ihc ihiiu
.n.,()). Each mcihou ucclaics onc local vaiiallc wiihin ihc louy
ol ihc mcihou, anu mcihou o() also ucclaics a aiamcici vaiiallc
which mcans o() has iwo local vaiiallcs).
s!zrk srcnzr|e
The method on the top of the
stack is always the currently-
executing method.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
238 chapter 9
Whz! z|ee! |erz| vzr|z||cs !hz! zrc e|jcr!s!
Rcmcmlci, a non-iimiiivc vaiiallc holus a .ee.ere io an
ol|cci, noi ihc ol|cci iiscll. You alicauy Inow whcic ol|ccis
livc-on ihc hca. Ii uocsn`i maiici whcic ihcy`ic ucclaicu oi
cicaicu. I[ the IocoI voriobIe is o re[erence to on object, onIy
the voriobIe )the re[erence,remote controI; goes on the stoch.
TLe obe .eI .II oe .r Le Len.
D
u
c
k ob
j
e
c
f
.-|`
--|`
public class StackRef {
public void foof() {
barf();
}
public void barf() {
Duck d = new Duck(24);
}
}
.-
|`
-:|.--: .-
:--.l
-: . ---
l
-: --
----:- .-.|- '
' |:-:- l
':
-:|.--
-:
- l
- -
-l
-
, l
': . |-:.|
.-.|- .-
--: -- l
- :l
.:
object references on the stack
8ll P0lk5
Anfenno
CeIIPhone objecf
CeIIPhone objecf
Anfenno objecf
CeIIPhone objecf
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
240 chapter 9
object creation
Ihc m|rzr|c ef e|jcr! rrcz!|en
Now ihai you Inow whcic vaiiallcs anu ol|ccis livc, wc can uivc inio
ihc mysiciious woilu ol ol|cci cicaiion. Rcmcmlci ihc ihicc sics
ol ol|cci ucclaiaiion anu assignmcni: ucclaic a iclcicncc vaiiallc,
cicaic an ol|cci, anu assign ihc ol|cci io ihc iclcicncc.
Bui uniil now, sic iwo-whcic a miiaclc occuis anu ihc ncw ol|cci
is loin"-has icmaincu a Big Mysiciy. Picaic io lcain ihc lacis ol
ol|cci lilc. Hoe ,ou`.e ro quen.L.
DecIore o reference
voriobIe
Duck reference
Duck reference
Duck objecf
M
.- . ---
--
----:-
.-.|- -
. :|.:: --
-l
--
.:- l
]-
A
-
-
.
:
|-
-
:
:
-
-
:
-
-
-
A
::- l
- ---
--:l
l
- l
-
--
----:-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 241
Are we calling a method named Duck{}?
Because it sure looks like it.
A consiiucioi Joe looI anu lccl a loi liIc a mcihou, lui ii`s noi
a mcihou. Ii`s goi ihc couc ihai iuns whcn you say new. In oihci
woius, Le oJe Ln .ur wLer ,ou .rnr.ne nr obe.
Thc only way io invoIc a consiiucioi is wiih ihc Icywoiu new
lollowcu ly ihc class namc. Thc ]VM hnus ihai class anu invoIcs
ihc consiiucioi in ihai class. OK, icchnically ihis isn`i ihc orI,
way io invoIc a consiiucioi. Bui ii`s ihc only way io uo ii liom
ou.Je a consiiucioi. You nr call a consiiucioi liom wiihin
anoihci consiiucioi, wiih icsiiiciions, lui wc`ll gci inio all ihai
laici in ihc chaici.)
Duck myDuck = new Duck();
|l |--: |- --'-- :.||-
. --l- -.-- l
-:|`,
-:.-:- - l- .---l-:-:
No.
We're calling the Duck constructor.
But where is the constructor?
f we didn't write it, who did?
You can wiiic a consiiucioi loi youi class wc`ic aloui io uo
ihai), lui il you uon`i, the compiIer writes one [or you:
Hcic`s whai ihc comilci`s uclauli consiiucioi looIs liIc:
public Duck() {
}
w---': l- --l--- l]- | l: ---- . --l-,
]--' --- . --l--- l]- -l---- -|:' .-
l-:|`'
Notice something missing? How is this
different from a method?
public Duck() {
// constructor code goes here
}
|l: -.-- : l- :.-- .: l-
:|.:: -.-- 1
.l': -.-.l--]
A censtracter has the
cede that rans when yea
instantiate an ebject. In
ether werds, the cede that
rans when yea say new en
a class type.
8very class yea create has
a censtracter, even if yea
den't write it yearself.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
242 chapter 9
constructing a new Duck
0ens!rer! z Perk
Thc Icy lcaiuic ol a consiiucioi is ihai ii iuns
ihc ol|cci can lc assigncu io a iclcicncc.
Thai mcans you gci a chancc io sic in anu
uo ihings io gci ihc ol|cci icauy loi usc. In
oihci woius, lcloic anyonc can usc ihc icmoic
coniiol loi an ol|cci, ihc ol|cci has a chancc io
hcl consiiuci iiscll. In oui DucI consiiucioi,
wc`ic noi uoing anyihing usclul, lui ii siill
ucmonsiiaics ihc scqucncc ol cvcnis.
If if Quocks Iike o
consfrucfor...
public class UseADuck {
public static void main (String[] args) {
Duck d = new Duck();
}
}
public class Duck {
public Duck() {
System.out.println(Quack);
}
}
File Edit Window Help Quack
% java UseADuck
Quack
c
--:l--:l-- :--
1
: :.||: l- l
-:
:--:l--:l--
The constructor gives
you a chance to step into
the middle of new.
+,-+ :+ ,-+:.|
A constructor lets you |ump into the middle
of the ob|ect creation stepinto the middle
of new. Can you imagine conditions where
that would be usefulI which of these might
be useful in a Car class constructor, if the Car
is part of a Pacing GameI Check off the ones
that you came up with a scenario for.
lrcrererl a courler lo lrac| |oW rary oojecls ol l||s c|ass lype
|ave oeer rade.
Ass|r rurl|re-spec|l|c slale (dala aooul W|al's |apper|r N0w).
Ass|r va|ues lo l|e oojecl's |rporlarl |rslarce var|ao|es.
0el ard save a relererce lo l|e oojecl l|al's orear|ng l|e reW oojecl.
Add l|e oojecl lo ar ArrayL|sl.
Creale lA3-A oojecls.
________________________________________ (your |dea |ere)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
constructors and gc
you are here 243
|n| !|z||z|n] !hc s!z!c ef z ncw Perk
Mosi colc usc consiiuciois io iniiializc ihc siaic ol an ol|cci.
In oihci woius, io maIc anu assign valucs io ihc ol|cci`s
insiancc vaiiallcs.
public Duck() {
size = 34;
}
Thai`s all wcll anu goou whcn ihc DucI class Je.eIoe. Inows
how lig ihc DucI ol|cci shoulu lc. Bui whai il wc wani ihc
iogiammci who is u.r DucI io ucciuc how lig a aiiiculai
DucI shoulu lc.
Imaginc ihc DucI has a sizc insiancc vaiiallc, anu you wani ihc
iogiammci using youi DucI class io sci ihc sizc ol ihc ncw
DucI. How coulu you uo ii.
Wcll, you coulu auu a sciSizc) sciici mcihou io ihc class. Bui
ihai lcavcs ihc DucI icmoiaiily wiihoui a sizc*, anu loiccs ihc
DucI usci io wiiic wo siaicmcnis-onc io cicaic ihc DucI, anu
onc io call ihc sciSizc) mcihou. Thc couc lclow uscs a sciici
mcihou io sci ihc iniiial sizc ol ihc ncw DucI.
public class Duck {
int size;
public Duck() {
System.out.println(Quack);
}
public void setSize(int newSize) {
size = newSize;
}
}
public class UseADuck {
public static void main (String[] args){
Duck d = new Duck();
d.setSize(42);
}
}
:--:l--:l--
-:l.-:- .-.|-
:-ll-- --l-
1---': . . l- --- 1- l
-: : .|- .l
l: --l - l- :--, -l -l--l . :--'
A- l-- ]--'-- --|]- -- l- l
-:~-:--
l- rN6w
l.l l
-: :--.l-- : . l--~.-l
--:-:: --- l- :.|| l- :--:l--:l-- .- ---
l- :.|| l- :-ll--
(-,- a,- |
oa|| qa--(:|-
Why do you need to write
a constructor if the compiIer
writes one for you!
|f you need code to help
initialize your ob|ect and get
it ready for use, you'll have to
write your own constructor. ou
might, for example, be depen-
dent on input from the user
before you can finish making
the ob|ect ready. There's another
reason you might have to write
a constructor, even if you don't
need any constructor code
yourself. |t has to do with your
superclass constructor, and we'll
talk about that in a few minutes.
How can you teII a con-
structor from a method! Can
you aIso have a method that's
the same name as the cIass!
1ava lets you declare a
method with the same name as
your class. That doesn't make it
a constructor, though. The thing
that separates a method from a
constructor is the return type.
Methods must have a return
type, but constructors connot
have a return type.
Are constructors inher-
ited! If you don't provide a
constructor but your supercIass
does, do you get the supercIass
constructor instead of the
defauIt!
Nope. Constructors are
not inherited. we'll look at that in
|ust a few pages.
*nstance variables do have a default value. 0 or
0.0 for numeric primitives, false for booleans, and
null for references.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
244 chapter 9
0s|n] !hc rens!rer!er !e |n| !|z||zc
|mper!zn! Perk s!z!c'
Il an ol|cci shoulun`i lc uscu uniil onc oi
moic aiis ol iis siaic insiancc vaiiallcs) havc
lccn iniiializcu, uon`i lci anyonc gci aholu ol
a DucI ol|cci uniil you`ic hnishcu iniiializing!
Ii`s usually way ioo iisIy io lci somconc maIc-
anu gci a iclcicncc io-a ncw DucI ol|cci ihai
isn`i quiic icauy loi usc uniil ihai somconc iuins
aiounu anu calls ihc eS..e() mcihou. How will
ihc DucI-usci cvcn Irow ihai hc`s icquiicu io call
ihc sciici mcihou alici maIing ihc ncw DucI.
Thc lcsi lacc io ui iniiializaiion couc is in ihc
consiiucioi. Anu all you nccu io uo is maIc a
consiiucioi wiih aigumcnis.
public class Duck {
int size;
public Duck(int duckSize) {
System.out.println(Quack);
size = duckSize;
System.out.println(size is + size);
}
}
public class UseADuck {
public static void main (String[] args) {
Duck d = new Duck(42);
}
}
File Edit Window Help Honk
% java UseADuck
Quack
size is 42
A
.
-
-
l
.
-
.
-
-
l
-
-
l
-
l
-
l
-
:
:
-
-
:l
-
-
:
l
-
-
:
l
-
-
l
-
-
-
':
-
-
|]
-
-
-
:l
.
l
-
-
-
-
l
w
-
-
.
-
l
-
-
-
-
l
-
:
.
-
:-
l
l
: :-
-
-
-
-
-
:l
.
l
-
-
-
-
l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 247
8ll P0lk5
----l
:--:l
--:l
--:
-
-.-:
---
----l
-
.]: l
-
-
.- . ---
-
-:
----
public class Mushroom {
public Mushroom(int size) { }
public Mushroom( ) { }
public Mushroom(boolean isMagic) { }
public Mushroom(boolean isMagic, int size) { }
public Mushroom(int size, boolean isMagic) { }
}
--- ]-- --- l- :--, -l ]--
--'l --- l': -.:
--- ]-- --'l --- .-]l-
--- ]-- --- l': -.: -- --l,
-l --'l --- l- :--
--- ]-- ---
--l-- -- --l l':
-.:, ANl ]-- ---
l- :-- .: --||
Overloaded constructors means you have
more than one constructor in your class.
To compile, each constructor must have a
different argument listl
Thc class lclow is lcgal lccausc all loui consiiuciois havc
uillcicni aigumcni lisis. Il you hau iwo consiiuciois ihai iooI
only an ini, loi cxamlc, ihc class woulun`i comilc. Whai you
namc ihc aiamcici vaiiallc uocsn`i couni. Ii`s ihc vaiiallc
,e ini, Dog, cic.) anu o.Je. ihai maiicis. You nr havc iwo
consiiuciois ihai havc iucniical iycs, os Iong os the order is
di[[erent. A consiiucioi ihai iaIcs a Siiing lollowcu ly an ini, is
ro ihc samc as onc ihai iaIcs an ini lollowcu ly a Siiing.
l-:- l-- .- l-
:.-- .-:, -l -
----l ----, :-
l': 6r
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
248 chapter 9
Animal
An|ma|
0bject
h|ppo
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
252 chapter 9
1
Code from onofher
cIoss soys new
Hippo()ond fhe
Hippo{} consfrucfor
goes info o sfock
frome of fhe fop of
fhe sfock.
+-|`
A--.||`
+-|`
2
Hippo{} invokes
fhe supercIoss
consfrucfor which
pushes fhe AnimuI{}
consfrucfor onfo fhe
fop of fhe sfock.
6-:l|`
+-|`
A--.||`
3 4
Object{} compIefes,
ond ifs sfock frome
is popped off fhe
sfock. Execufion goes
bock fo fhe AnimuI{}
consfrucfor, ond
picks up of fhe Iine
foIIowing AnimoI's
coII fo ifs supercIoss
consfrucfor
AnimuI{} invokes
fhe supercIoss
consfrucfor which
pushes fhe Object{}
consfrucfor onfo
fhe fop of fhe sfock,
since Objecf is fhe
supercIoss of AnimoI.
A--.||`
+-|`
Mzk|n] z H|ppe mczns mzk|n] !hc
n|mz| zn4 0|jcr! pzr!s !ee...
public class Animal {
public Animal() {
System.out.println(Making an Animal);
}
}
public class Hippo extends Animal {
public Hippo() {
System.out.println(Making a Hippo);
}
}
public class TestHippo {
public static void main (String[] args) {
System.out.println(Starting...);
Hippo h = new Hippo();
}
}
File Edit Window Help Swear
% java TestHippo
Starting...
Making an Animal
Making a Hippo
File Edit Window Help Swear
% java TestHippo
Starting...
Making a Hippo
Making an Animal
+,-+ :+ ,-+:.|
A
B
what's the real outputI Given the
code on the left, what prints out
when you run TestHippoI A or 8I
(the answer is at the bottom of the page)
object construction
T | e l | r s l o r e , A . T | e l | p p o ( ) c o r s l r u c l o r | s | r v o | e d l | r s l , o u l
| l ' s l | e A r | r a | c o r s l r u c l o r l | a l l | r | s | e s l | r s l .
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
constructors and gc
you are here 253
Hew 4e yee |nvekc z sepcrr|zss rens!rer!er!
And how is it that we've
gotten away without
doing it?
You mighi ihinI ihai somcwhcic in, say, a DucI consiiucioi,
il DucI cxicnus Animal you`u call Animal). Bui ihai`s noi
how ii woiIs:
public class Duck extends Animal {
int size;
public Duck(int newSize) {
Animal();
size = newSize;
}
}
N
6
' 1
: : --l |-.|'
B
A
l
'
Thc only way io call a suci consiiucioi is ly calling super);.
Thai`s iighi-super); calls ihc super constructor.
Whai aic ihc ouus.
public class Duck extends Animal {
int size;
public Duck(int newSize) {
super();
size = newSize;
}
}
]-- -:l :.] :---|`
A call io ue.() in youi consiiucioi uis ihc suciclass
consiiucioi on ihc io ol ihc SiacI. Anu whai uo you
ihinI ihai suciclass consiiucioi uocs. CnII . ue.In
or.uo.. Anu so ii gocs uniil ihc Ol|cci consiiucioi is
on ihc io ol ihc SiacI. Oncc Obe() hnishcs, ii`s ocu
oll ihc SiacI anu ihc ncxi ihing uown ihc SiacI ihc
sulclass consiiucioi ihai callcu Obe()) is now on io.
TLn consiiucioi hnishcs anu so ii gocs uniil ihc oiiginal
consiiucioi is on ihc io ol ihc SiacI, whcic . can now
hnish.
ou probably figured that out.
Dur good friend the compiIer
puts in a caII to suer(} if you
don't.
So the compiler gets involved in
constructor-making in two ways:
The compiler puts one in that looks like:
public ClassName() {
super();
}
The compiler will put a call to super() in
each of your overloaded constructors.`
The compiler-supplied call looks like:
super();
|t always looks like that. The compiler-
inserted call to suet(} is always a no-arg
call. |f the superclass has overloaded
constructors, only the no-arg one is called.
1
2
If you Jenr provide a constructor
If you Je provide a constructor
but you do ner put in the caII to
super()
ur|ess l|e corslruclor ca||s arol|er over|oaded
corslruclor (you'|| see l|al |r a leW paes).
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
object IifecycIe
254 chapter 9
0zn !hc rh||4 cr|s! |cferc
!hc pzrcn!s!
Il you ihinI ol a suciclass as ihc aicni io ihc sulclass chilu,
you can hguic oui which has io cxisi hisi. The supercIoss ports
o[ on object hove to be [uIIy-[ormed )compIeteIy buiIt; be[ore the
subcIoss ports con be constructed. Rcmcmlci,
ihc sulclass ol|cci mighi uccnu on ihings ii
inhciiis liom ihc suciclass, so ii`s imoiiani
ihai ihosc inhciiicu ihings lc hnishcu. No
way aiounu ii. Thc suciclass consiiucioi
musi hnish lcloic iis sulclass consiiucioi.
IooI ai ihc SiacI sciics on agc 24S again,
anu you can scc ihai whilc ihc Hio
consiiucioi is ihc io lc invoIcu ii`s
ihc hisi ihing on ihc SiacI), ii`s ihc onc
io comlcic! Each sulclass consiiucioi
immcuiaicly invoIcs iis own suciclass
consiiucioi, uniil ihc Ol|cci consiiucioi
is on ihc io ol ihc SiacI. Thcn Ol|cci`s
consiiucioi comlcics anu wc louncc
lacI uown ihc SiacI io Animal`s
consiiucioi. Only alici Animal`s consiiucioi comlcics
uo wc hnally comc lacI uown io hnish ihc icsi ol ihc Hio
consiiucioi. Ioi ihai icason:
The call to super{} must be the hrst statement
in each constructorl*
Eewwww... fhof
is SO creepy. There's
woy I couId hove been
born before my porenfs.
Thof's jusf wrong.
*There's an exception to this rule; you'll learn it on page 252.
PossibIe consfrucfors for cIoss 8oop
public Boop() {
super();
}
public Boop(int i) {
super();
size = i;
}
1-:- .-- 6r -:.-:-
l- ---.---- -~ |:l|] :-- l- :.||
l- :---|`, .: l- -:l
:l.l----l
public Boop() {
}
public Boop(int i) {
size = i;
}
public Boop(int i) {
size = i;
super();
}
1-:- .-- 6r -:.-:-
l- :--|-- -|| -l .
:.|| l- :---|` - .: l-
-:l :l.l----l
BAl
'' 1: ---'l :--|-'
/-- :.-'l -|:l|] -l
l- :.|| l- :---|` -|--
.-]l- -|:-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 255
8epcrr|zss rens!rer!ers w| !h zr]emcn!s
Whai il ihc suciclass consiiucioi has aigumcnis. Can you ass somcihing in io
ihc ue.() call. Ol couisc. Il you coulun`i, you`u ncvci lc allc io cxicnu a class
ihai uiun`i havc a no-aig consiiucioi. Imaginc ihis sccnaiio: all animals havc a
namc. Thcic`s a eNne() mcihou in class Animal ihai iciuins ihc valuc ol ihc
rne insiancc vaiiallc. Thc insiancc vaiiallc is maiIcu iivaic, lui ihc sulclass
in ihis casc, Hio) inhciiis ihc eNne() mcihou. So hcic`s ihc iollcm:
Hio has a eNne() mcihou ihiough inhciiiancc), lui uocs noi havc ihc rne
insiancc vaiiallc. Hio has io uccnu on ihc Animal aii ol himscll io Icc ihc
namc insiancc vaiiallc, anu iciuin ii whcn somconc calls eNne() on a Hio
ol|cci. Bui... how uocs ihc Animal aii gci ihc namc. Thc only iclcicncc Hio
has io ihc Animal aii ol himscll is ihiough ue.(), so ihai`s ihc lacc whcic
Hio scnus ihc Hio`s namc u io ihc Animal aii ol himscll, so ihai ihc
Animal aii can sioic ii in ihc iivaic rne insiancc vaiiallc.
l|ppo(3lr|r r)
[ol|er l|ppo-spe-
c|l|c rel|ods|
public abstract class Animal {
private String name;
public String getName() {
return name;
}
public Animal(String theName) {
name = theName;
}
}
A -ll-- --l- l.l +- ---l:
1- :--:l--:l-- l.l l.-: l- -.-- .- .::-:
l l- -.-- -:l.-:- .-.|-
A|| .--.|: |-:|--
:-:|.::-:` .- . -.--
public class Hippo extends Animal {
public Hippo(String name) {
super(name);
}
}
public class MakeHippo {
public static void main(String[] args) {
Hippo h = new Hippo(Buffy);
System.out.println(h.getName());
}
}
+- :--:l--:l-- l.-: . -.--
l :--: l- -.-- - l- l.: l-
l- A--.| :--:l--:l--
The AnimoI porf of
me needs fo know my nome,
so I foke o nome in my own
Hippo consfrucfor, fhen poss
fhe nome fo super()
M.- . +-, .::- l-
-.-- B-]' l- l- +-
:--:l--:l-- 1-- :.|| l-
+-': ---l- -lN.--|`
File Edit Window Help Hide
%java MakeHippo
Buffy
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
256 chapter 9
|nvek|n] enc evcr|ez4c4 rens!rer!er
frem zne!hcr
Whai il you havc ovciloaucu consiiuciois ihai, wiih
ihc cxcciion ol hanuling uillcicni aigumcni iycs,
all uo ihc samc ihing. You Inow ihai you uon`i wani
JuI.ne couc siiiing in cach ol ihc consiiuciois ain
io mainiain, cic.), so you`u liIc io ui ihc lulI ol ihc
consiiucioi couc incluuing ihc call io suci)) in only
ore ol ihc ovciloaucu consiiuciois. You wani whichcvci
consiiucioi is hisi invoIcu io call Thc Rcal Consiiucioi
anu lci Thc Rcal Consiiucioi hnish ihc |ol ol
consiiuciion. Ii`s simlc: |usi say L.(). Oi L.(nS..r).
Oi L.(27, :). In oihci woius, |usi imaginc ihai ihc
Icywoiu L. is a iclcicncc io thc currcnt objcct
You can say L.() only wiihin a consiiucioi, anu ii musi
lc ihc hisi siaicmcni in ihc consiiucioi!
Bui ihai`s a iollcm, isn`i ii. Eailici wc saiu ihai
suci) musi lc ihc hisi siaicmcni in ihc consiiucioi.
Wcll, ihai mcans you gci a choicc.
Every constructor can have a call to super{}
or this{}, but never bothl
caIIing overIoaded constructors
class Mini extends Car {
Color color;
public Mini() {
this(Color.Red);
}
public Mini(Color c) {
super(Mini);
color = c;
// more initialization
}
public Mini(int size) {
this(Color.Red);
super(size);
}
}
l
se th:sl I ta :a|| a
:aast:a:ta: I:a
aaathe:
ave:|aaJeJ :aast:a:ta: :a
the sa
e :|ass.
T
he :a|| ta th:sl I
:aa le aseJ aa|y :a a
:aast:a:ta:, aaJ
ast le
the I ::st state
eat :a a
:aast:a:ta:.
A
:aast:a:ta: :aa have a
:a|| ta sae:l I 0
k
th:sl I,
lat aeve: lath!
1- --~.- :--:l--:l--
:-|-: . -.-|l c-|-- .-
:.||: l- ---|-.- -.|
c--:l--:l-- |l- --- l.l
:.||: :---|``
1: : 1- -.| c--:l--:l-- l.l
--: 1- -.| w-- - -l.|-- l-
--:l |-:|-- l- :.|| l- :---|``
File Edit Window Help Drive
javac Mini.java
Mini.java:16: call to super must
be first statement in constructor
super();
^
w--'l ---'' c.-'l .-
:---|` .- l:|` - l- :.--
:--:l--:l--, -:.-:- l-] -.:
--:l - l- -:l :l.l----l'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 257
+,-+ :+ ,-+:.|
public class Boo {
public Boo(int i) { }
public Boo(String s) { }
public Boo(String s, int i) { }
}
class SonOfBoo extends Boo {
public SonOfBoo() {
super(boo);
}
public SonOfBoo(int i) {
super(Fred);
}
public SonOfBoo(String s) {
super(42);
}
public SonOfBoo(int i, String s) {
}
public SonOfBoo(String a, String b, String c) {
super(a,b);
}
public SonOfBoo(int i, int j) {
super(man, j);
}
public SonOfBoo(int i, int x, int y) {
super(i, star);
}
}
Some of the constructors in the SonOf8oo class will not
compile. See if you can recognize which constructors are
not legal. Match the compiler errors with the SonOf8oo
constructors that caused them, by drawing a line from the
compiler error to the "bad constructor.
File Edit Window Help mNotListening
%javac SonOfBoo.java
cannot resolve symbol
symbol:constructor Boo()
File Edit Window Help
%javac SonOfBoo.java
cannot resolve symbol
symbol : constructor Boo
(java.lang.String,java.la
ng.String)
File Edit Window Help Yadayadayada
%javac SonOfBoo.java
cannot resolve symbol
symbol : constructor Boo
(int,java.lang.String)
.
| l
-
-
:-
':'
-
-
-
'
1
- .-.|- ':' : .|-, -l - ::-- --|] -l- l-
--.|` -
-l- w
-- :|--|` :--
|-l-: .- --.|` :
-- l- - l- l.: .- ----- ..-, --.|` :.-
:l|| :-- ':' w
-- --.|` :--
|-l-: .- : -- -
l- l.:, ':' : -. |-:- - l.| .:-:
:|--|` :.-'l :-- l- ':' .-.|- -:-
l': --l - :|--|`': --- l.: -.--,
:|--|` --:-'l --- .-]l- .--l l
object Iifespan
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 259
public void doStuff() {
boolean b = true;
go(4);
}
public void go(int x) {
int z = x + 24;
crazy();
// imagine more code here
}
public void crazy() {
char c = `a';
}
-l-|`
-|`
-l-|`
-
:-.-]|`
:
-l-|`
-|` -
-|`
-l-|`
-
1
do3tuff[} goes on the
8tack. Var|ab|e 'b' |s
a||ve and |n scope.
go[} p|ops on top of
the 8tack. 'x' and 'z'
are a||ve and |n scope,
and 'b' |s a||ve but not
|n scope.
crezy[} |s pushed onto
the 8tack, w|th 'c' now
a||ve and |n scope. The
other three var|ab|es
are a||ve but out of
scope.
crezy[} comp|etes and
|s popped off the 8tack,
so 'c' |s out of scope
end deed. when go(}
resumes where |t |eft
off, 'x' and 'z' are both
a||ve and back |n scope.
Var|ab|e 'b' |s st||| a||ve
but out of scope (unt||
go(} comp|etes}.
Life
8cope
A local vaiiallc is nI..e as long as iis SiacI
liamc is on ihc SiacI. In oihci woius,
ur.I Le eLoJ oIee.
A local vaiiallc is in oe only wiihin ihc
mcihou in which ihc vaiiallc was ucclaicu.
Whcn iis own mcihou calls anoihci, ihc
vaiiallc is alivc, lui noi in scoc uniil iis
mcihou icsumcs. You con use o voriobIe onIy
when it is in scope.
The difference between life and
scope for IocaI variabIes:
2 3 4
Whilc a local vaiiallc is alivc, iis siaic cisisis.
As long as mcihou uoSiull) is on ihc SiacI, loi
cxamlc, ihc l` vaiiallc Iccs iis valuc. Bui ihc
l` vaiiallc can lc uscu only whilc uoSiull)`s
SiacI liamc is ai ihc io. In oihci woius, you can
usc a local vaiiallc orI, whilc ihai local vaiiallc`s
mcihou is aciually iunning as ooscu io
waiiing loi highci SiacI liamcs io comlcic).
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
object IifecycIe
260 chapter 9
Thc iulcs aic ihc samc loi iimiivcs anu iclcicnccs. A iclcicncc
vaiiallc can lc uscu only whcn ii`s in scoc, which mcans you can`i usc
an ol|cci`s icmoic coniiol unlcss you`vc goi a iclcicncc vaiiallc ihai`s
in scoc. Thc .enI qucsiion is,
How docs voriobIe liIc aIIcct object liIc?
An ol|cci is alivc as long as ihcic aic livc iclcicnccs io ii. Il a iclcicncc
vaiiallc gocs oui ol scoc lui is siill alivc, ihc ol|cci ii .ee. io is siill
alivc on ihc Hca. Anu ihcn you havc io asI... Whai hacns whcn ihc
SiacI liamc holuing ihc iclcicncc gcis ocu oll ihc SiacI ai ihc cnu
ol ihc mcihou."
Il ihai was ihc orI, livc iclcicncc io ihc ol|cci, ihc ol|cci is now
alanuoncu on ihc Hca. Thc iclcicncc vaiiallc uisinicgiaicu wiih
ihc SiacI liamc, so ihc alanuoncu ol|cci is now, o.nII,, ioasi. Thc
iiicI is io Inow ihc oini ai which an ol|cci lccomcs eIigibIe [or gorboge
coIIection.
Oncc an ol|cci is cligillc loi gailagc collcciion GC), you uon`i havc
io woiiy aloui icclaiming ihc mcmoiy ihai ol|cci was using. Il youi
iogiam gcis low on mcmoiy, GC will ucsiioy somc oi all ol ihc cligillc
ol|ccis, io Icc you liom iunning oui ol RAM. You can siill iun oui ol
mcmoiy, lui ro lcloic all cligillc ol|ccis havc lccn haulcu oll io ihc
uum. Youi |ol is io maIc suic ihai you alanuon ol|ccis i.c, maIc
ihcm cligillc loi GC) whcn you`ic uonc wiih ihcm, so ihai ihc gailagc
collccioi has somcihing io icclaim. Il you hang on io ol|ccis, GC can`i
hcl you anu you iun ihc iisI ol youi iogiam uying a ainlul
oui-ol-mcmoiy ucaih.
Whz! z|ee! rcfcrcnrc vzr|z||cs!
aa eoeets ||Ie bas ae
va|ue, ae meaa|ag, ae
pe|at, ua|ess semeoeay
bas a reIereaee te |t.
tI yeu eaat get te |t,
yeu eaat ass |t te ae
aaytb|ag aaa |ts ust a
o|g Iat waste eI o|ts.
sut |I aa eoeet |s
uareaebao|e, tbe
aaroage ce||eeter w|||
gure tbat eut. seeaer
er |ater, tbat eoeets
ge|a aewa.
An ob]ect becomes
eligible for GC when
its last live reference
disappears.
Three ways to get rid of an ob]ect's reference:
1 The reference goes ouf of scope, permonenfIy
2 The reference is ossigned onofher objecf
3 The reference is expIicifIy sef fo nuII
void go() {
Life z = new Life();
}
Life z = new Life();
z = new Life();
Life z = new Life();
z = null;
------:- '-' -: .l
-- - --l-
l- -:l --:l : ..----
--- - : '-----.---' l-
. --- --:l
l- -:l --:l : ..----
--- - : '----.---'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 261
public class StackRef {
public void foof() {
barf();
}
public void barf() {
Duck d = new Duck();
}
}
D
u
c
k ob
j
e
c
f
.-|`
--|`
+
-
.
--|`
|s pushed onto the
8tack, no var|ab|es are
dec|ared.
1
|s pushed onto the
8tack, where |t dec|ares
a reference var|ab|e, and
creates a new object as-
s|gned to that reference.
The object |s created on
the heap, and the refer-
ence |s a||ve and |n scope.
2
--|`
comp|etes and pops
off the 8tack. |ts frame
d|s|ntegrates, so 'd' |s now
dead and gone. Execut|on
returns to , but
can't use 'd' .
3
D
u
c
k ob
j
e
c
f
+
-
.
1
- --- l
-: --: -- l-
+-., .- .: |-- .: .-|`
: -----, l- '' ------:-
: .|- .- - ::--, :- l-
l
-: : :--:--- .|-
c~- 1- '' .-.|-
---l .-.] --- l- .-|`
l.: -.-- -.: |---
- l- :l.:, :- l- l-:
: ..---- 6.-.-~
:-||-:l-- .l
I don'f Iike where
fhis is heoded.
Ob]ect-killer #1
Reference goes
out of scope,
permanently.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
object IifecycIe
262 chapter 9
Ob]ect-killer #2
Assign the reference
to another ob]ect
Dude, oII you
hod fo do wos resef
fhe reference. 0uess
fhey didn'f hove memory
monogemenf bock fhen.
public class ReRef {
Duck d = new Duck();
public void go() {
d = new Duck();
}
}
1- --- l-: --: -- l- +-., ------:-
] '' -:- '' : .- -:l.-:- .-.|-, l-
l-: -|| |- .: |-- .: l- -- --:l
l.l -:l.-l.l- l : .|- c-|-::
D
u
c
k ob
j
e
c
f
+
-
.
1
'' : .::-- . --- l-: --:l, |-.- l-
---.| |-:l` l-: --:l ..---- 1.l
-:l l-: : --- .: -- .: -.
D
u
c
k ob
j
e
c
f
+
-
.
D
u
c
k ob
j
e
c
f
w-- :------ :.||: l-
-|` --l-, l: l-: :
..---- +: --|] ------:-
.: --- -----.--- -- .
----l l-:
P
e
P
e
f ob
j
e
c
f
P
e
P
e
f ob
j
e
c
f
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
constructors and gc
you are here 263
Ob]ect-killer #3
Explicitly set the
reference to null
public class ReRef {
Duck d = new Duck();
public void go() {
d = null;
}
}
1- --- l-: --: -- l- +-., ------:-
] '' -:- '' : .- -:l.-:- .-.|-, l-
l-: -|| |- .: |-- .: l- -- --:l
l.l -:l.-l.l- l : .|- c-|-::
D
u
c
k ob
j
e
c
f
+
-
.
1: l-: : ..----
+: --|] ------:- .: ---
:-l l- --||
The meaning of null
when you set a reference to null, you're
deprogramming the remote control.
|n other words, you've got a remote
control, but no Tv at the other end. A null
reference has bits representing 'null' (
don't know or care what those bits are, as
long as the 1vM knows).
|f you have an unprogrammed remote
control, in the real world, the buttons don't
do anything when you press them. 8ut
in 1ava, you can't press the buttons (i.e.
use the dot operator) on a null reference,
because the 1vM knows (this is a runtime
issue, not a compiler error) that you're
expecting a bark but there's no Dog there
to do it!
If you use the dot operator on
a nuII reference, you'II get a
NuIIPointerxception at runtime. ou'll
learn all about Lxceptions in the Pisky
8ehavior chapter.
P
e
P
e
f ob
j
e
c
f
P
e
P
e
f ob
j
e
c
f
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
object IifecycIe
264 chapter 9
Instance Variable
I`u liIc io go hisi, lccausc I icnu io lc moic
imoiiani io a iogiam ihan a local vaiiallc.
I`m ihcic io suoii an ol|cci, usually
ihioughoui ihc ol|cci`s cniiic lilc. Alici all,
whai`s an ol|cci wiihoui ne. Anu whai is
siaic. Valucs Ici in instonce voriobIes.
No, uon`i gci mc wiong, I uo unucisianu youi
iolc in a mcihou, ii`s |usi ihai youi lilc is so
shoii. So icmoiaiy. Thai`s why ihcy call you
guys icmoiaiy vaiiallcs".
My aologics. I unucisianu comlcicly.
I ncvci ically ihoughi aloui ii liIc ihai. Whai
aic you uoing whilc ihc oihci mcihous aic
iunning anu you`ic waiiing loi youi liamc io
lc ihc io ol ihc SiacI again.
Lecal Variable
I aicciaic youi oini ol vicw, anu I cciiainly
aicciaic ihc valuc ol ol|cci siaic anu all,
lui I uon`i wani lolIs io lc mislcu. Iocal
vaiiallcs aic .enII, imoiiani. To usc youi
hiasc, Alici all, whai`s an ol|cci wiihoui
beLn..o.." Anu whai is lchavioi. Algoiiihms
in mcihous. Anu you can lci youi liis ihcic`ll
lc somc IonI .n..nbIe in ihcic io maIc ihosc
algoiiihms woiI.
Wiihin ihc local-vaiiallc communiiy, ihc
hiasc icmoiaiy vaiiallc" is consiucicu
uciogaioiy. Wc iclci local", siacI", auio-
maiic", oi "Scoc-challcngcu".
Anyway, ii`s iiuc ihai wc uon`i havc a long
lilc, anu ii`s noi a aiiiculaily ooJ lilc ciihci.
Iiisi, wc`ic shovcu inio a SiacI liamc wiih
all ihc oihci local vaiiallcs. Anu ihcn, il ihc
mcihou wc`ic aii ol calls anoihci mcihou,
anoihci liamc is ushcu on io ol us. Anu il
Ln mcihou calls nroLe. mcihou... anu so on.
Somciimcs wc havc io waii loicvci loi all ihc
oihci mcihous on io ol ihc SiacI io com-
lcic so ihai oui mcihou can iun again.
Noihing. Noihing ai all. Ii`s liIc lcing in
siasis-ihai ihing ihcy uo io colc in scicncc
hciion movics whcn ihcy havc io iiavcl long
uisianccs. Suscnucu animaiion, ically. Wc
|usi sii ihcic on holu. As long as oui liamc is
siill ihcic, wc`ic salc anu ihc valuc wc holu
is sccuic, lui ii`s a mixcu llcssing whcn oui
1cnih|`s 1alk: An instance variable and
a lecal variable discass life and death
{with remarkable civility}
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 265
Wc saw an cuucaiional viuco aloui ii oncc.
IooIs liIc a iciiy liuial cnuing. I mcan,
whcn ihai mcihou hiis iis cnuing cuily liacc,
ihc liamc is liicially bIowr oll ihc SiacI! Now
Ln` goiia huii.
I livc on ihc Hca, wiih ihc ol|ccis. Wcll, noi
w.L ihc ol|ccis, aciually .r an ol|cci. Thc
ol|cci whosc siaic I sioic. I havc io aumii lilc
can lc iciiy luxuiious on ihc Hca. A loi ol
us lccl guiliy, csccially aiounu ihc holiuays.
OK, hyoihciically, ycs, il I`m an insiancc
vaiiallc ol ihc Collai anu ihc Collai gcis
GC`u, ihcn ihc Collai`s insiancc vaiiallcs
woulu inuccu lc iosscu oui liIc so many izza
loxcs. Bui I was iolu ihai ihis almosi ncvci
hacns.
Thcy lci us J..rI.
liamc gcis io iun again. On ihc onc hanu, wc
gci io lc aciivc again. On ihc oihci hanu, ihc
clocI siaiis iicIing again on oui shoii livcs.
Thc moic iimc oui mcihou scnus iunning,
ihc closci wc gci io ihc cnu ol ihc mcihou.
Wc nII Inow whai hacns ihcn.
Tcll mc aloui ii. In comuici scicncc ihcy usc
ihc icim oeJ as in ihc liamc was ocu
oll ihc SiacI". Thai maIcs ii sounu lun, oi
maylc liIc an cxiicmc soii. Bui, wcll, you
saw ihc looiagc. So why uon`i wc ialI aloui
you. I Inow whai my liiilc SiacI liamc looIs
liIc, lui whcic uo ,ou livc.
Bui you uon`i nIwn, livc as long as ihc ol|cci
who ucclaicu you, iighi. Say ihcic`s a Dog
ol|cci wiih a Collai insiancc vaiiallc. Imaginc
,ou`.e an insiancc vaiiallc ol ihc CoIIn. ol|cci,
maylc a iclcicncc io a BucIlc oi somcihing,
siiiing ihcic all hay insiuc ihc CoIIn. ol|cci
who`s all hay insiuc ihc Do ol|cci. Bui...
whai hacns il ihc Dog wanis a ncw Collai,
oi ruII oui iis Collai insiancc vaiiallc. Thai
maIcs ihc Collai ol|cci cligillc loi GC. So...
il ,ou`.e an insiancc vaiiallc insiuc ihc Collai,
anu ihc wholc CoIIn. is alanuoncu, whai
hacns io ,ou.
Anu you lclicvcu ii. Thai`s whai ihcy say io
Icc us moiivaicu anu iouuciivc. Bui aicn`i
you loigciiing somcihing clsc. Whai il you`ic
an insiancc vaiiallc insiuc an ol|cci, anu ihai
ol|cci is iclcicnccu orI, ly a IonI vaiiallc. Il
I`m ihc only iclcicncc io ihc ol|cci you`ic in,
whcn I go, you`ic coming wiih mc. IiIc ii oi
noi, oui laics may lc connccicu. So I say wc
loigci aloui all ihis anu go gci uiunI whilc
wc siill can. Caic RAM anu all ihai.
1nstance VarIabIe LccaI VarIabIe
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
266 chapter 9
y[je[ | ([ ]jn, | e] n ([ jg[(, j| z]]]
( ([ e]z,, n ([ ]|( z( jn( j, wa]] eza,
yze(]y n z]]j(jnz] je( ( ]jgj] | ([
(zzg (]]e(/ (j,,a ([z( jn( j (//ez]]
([],) wj]] yea( | z ]ng (j, gjvjng ([
(zzg (]]e( (j ( ] j(, ,(a||.)
] ge (;ge [o||eeo;
public class GC {
public static GC doStuff() {
GC newGC = new GC();
doStuff2(newGC);
return newGC;
}
public static void main(String [] args) {
GC gc1;
GC gc2 = new GC();
GC gc3 = new GC();
GC gc4 = gc3;
gc1 = doStuff();
// call more methods
}
public static void doStuff2(GC copyGC) {
GC localGC = copyGC;
}
}
File Edit Window Help Sleep
I
Z
3
4
b
o
7
8
9
copyGC = null;
gc2 = null;
newGC = gc3;
gc1 = null;
newGC = null;
gc4 = null;
gc3 = gc2;
gc1 = gc4;
gc3 = null;
exercise: Be the Garbage CoIIector
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 267
class Bees {
Honey beeHA,
}
class Raccoon {
Kit k,
Honey rh,
}
class Kit {
Honey kh,
}
class Bear {
Honey hunny,
}
public class Honey {
public static void main{String args| {
Honey honeyPot = new Honey{|,
Honey ha = {honeyPot, honeyPot, honeyPot, honeyPot},
Bees bl = new Bees{|,
bl.beeHA = ha,
Bear ba = new Bear5,
for {int x=0, x < 5, x++| {
bax = new Bear{|,
bax.hunny = honeyPot,
}
Kit k = new Kit{|,
k.kh = honeyPot,
Raccoon r = new Raccoon{|,
r.rh = honeyPot,
r.k = k,
k = null,
} // end of main
}
]a[|i
ubjcc[s
|n this code example, several new ob|ects are created.
our challenge is to find the ob|ect that is 'most popular',
i.e. the one that has the most reference variables referring
to it. Then list how total references there are for
that ob|ect, and what they are! we'll start by pointing out
one of the new ob|ects, and its reference variable.
Good Luck !
Here's u new
Puccoon object|
Here's its reference
vuriubIe 'r',
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
268 chapter 9
]Jc_Jna[c
_s[ci
'We`ve run the simulation four times, and the main module`s temperature consistently
drifts out of nominal towards cold, Sarah said, exasperated. 'We installed the new temp-bots last
week. The readings on the radiator bots, designed to cool the living quarters, seem to be within
spec, so we`ve focused our analysis on the heat retention bots, the bots that help to warm the quar-
ters. Tom sighed, at frst it had seemed that nano-technology was going to really put them ahead
of schedule. Now, with only fve weeks left until launch, some of the orbiter`s key life support
systems were still not passing the simulation gauntlet.
'What ratios are you simulating?, Tom asked.
'Well if I see where you`re going, we already thought of that, Sarah replied. 'Mis-
sion control will not sign off on critical systems if we run them out of spec. We are
required to run the v3 radiator bot`s SimUnits in a 2:1 ratio with the v2 radiator`s
SimUnits, Sarah continued. 'Overall, the ratio of retention bots to radiator bots is
supposed to run 4:3.
'How`s power consumption Sarah?, Tom asked. Sarah paused, 'Well that`s
another thing, power consumption is running higher than anticipated. We`ve got a team
tracking that down too, but because the nanos are wireless it`s been hard to isolate the power
consumption of the radiators from the retention bots. 'Overall power consumption ratios, Sarah
continued, 'are designed to run 3:2 with the radiators pulling more power from the wireless grid.
'OK Sarah, Tom said 'Let`s take a look at some of the simulation initiation code.
We`ve got to fnd this problem, and fnd it quick!
import ava.util.*,
class V2Radiator {
V2Radiator{ArrayList list| {
for{int x=0, x<5, x++| {
list.add{new SimUnit{"V2Radiator"||,
}
}
}
class V3Radiator extends V2Radiator {
V3Radiator{ArrayList lglist| {
super{lglist|,
for{int g=0, g<l0, g++| {
lglist.add{new SimUnit{"V3Radiator"||,
}
}
}
class RetentionBot {
RetentionBot{ArrayList rlist| {
rlist.add{new SimUnit{"Retention"||,
}
}
puzzIe: Five Minute Mystery
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 269
public class TestLifeSupportSim {
public static void main{String args| {
ArrayList aList = new ArrayList{|,
V2Radiator v2 = new V2Radiator{aList|,
V3Radiator v3 = new V3Radiator{aList|,
for{int z=0, z<20, z++| {
RetentionBot ret = new RetentionBot{aList|,
}
}
}
class SimUnit {
String botType,
SimUnit{String type| {
botType = type,
}
int powerUse{| {
if {"Retention".equals{botType|| {
return 2,
} else {
return 4,
}
}
}
Tom gave the code a quick look and a small smile creeped across his lips. I think I`ve
found the problem Sarah, and I bet I know by what percentage your power usage readings are off
too!
What did Tom suspect? How could he guess the power readings errors, and what few
lines of code could you add to help debug this program?
]Jc_Jna[c
_s[ci
cn[Jnacc...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
object IifecycIe
270 chapter 9
public class Honey {
public static void main{String args| {
Honey honeyPot = new Honey{|,
Honey ha = {honeyPot, honeyPot,
honeyPot, honeyPot},
Bees bl = new Bees{|,
bl.beeHA = ha,
Bear ba = new Bear5,
for {int x=0, x < 5, x++| {
bax = new Bear{|,
bax.hunny = honeyPot,
}
Kit k = new Kit{|,
k.kh = honeyPot,
Raccoon r = new Raccoon{|,
r.rh = honeyPot,
r.k = k,
k = null,
} // end of main
}
Honey
Objecf
( ends up nuII )
]a[|i
ubjcc[s
|t probably wasn't too hard to gure out that the Honey ob|ect rst referred to by the honeyPot variable is by
far the most 'popular' ob|ect in this class. 8ut maybe it was a little trickier to see that all of the variables that
point from the code to the Honey ob|ect refer to the snme ebjecr! There are a total of l2 active references to
this ob|ect right before the main( ) method completes. The variable is valid for a while, but k gets nulled
at the end. Since still refers to the Kit ob|ect, (although never explicity declared), refers to the ob|ect!
I
Z
3
4
b
o
7
8
9
copyGC = null;
gc2 = null;
newGC = gc3;
gc1 = null;
newGC = null;
gc4 = null;
gc3 = gc2;
gc1 = gc4;
gc3 = null;
Mo - fhis Iine offempfs fo occess o voriobIe
fhof is ouf of scope.
OI - gcZ wos fhe onIy reference voriobIe
referring fo fhof objecf.
Mo - onofher ouf of scope voriobIe.
OI - gcI hod fhe onIy reference becouse
new0C is ouf of scope.
Mo - new0C is ouf of scope.
Mo - gc3 is sfiII referring fo fhof objecf.
Mo - gc4 is sfiII referring fo fhof objecf.
OI - Peossigning fhe onIy reference fo
fhof objecf.
Mo - gc4 is sfiII referring fo fhof objecf.
(.[.
]e;ejze o|ajoz
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
constructors and gc
you are here 271
]Jc_Jna[c _s[ci [a[Jn
Tom noticed that the constructor for the V2Radiator class took an
ArrayList. That meant that every time the Radiator constructor was called,
it passed an ArrayList in its super() call to the Radiator constructor. That
meant that an extra fve V2Radiator SimUnits were created. If Tom was right,
total power use would have been 120, not the 100 that Sarah`s expected ratios
predicted.
Since all the Bot classes create SimUnits, writing a constructor for
the SimUnit class, that printed out a line everytime a SimUnit was created,
would have quickly highlighted the problem!
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
this is a new chapter 273
10 numbers and statics
Numbers Matter
Do the Math. 8ut there's more to working with numbers than |ust doing primitive
arithmetic. ou might want to get the absolute value of a number, or round a number, or find
the larger of two numbers. ou might want your numbers to print with exactly two decimal
places, or you might want to put commas into your large numbers to make them easier to read.
And what about working with datesI ou might want to print dates in a variety of ways, or even
mon|ulote dates to say things like, "add three weeks to today's date. And what about parsing
a String into a numberI Or turning a number into a StringI ou're in luck. The 1ava AP| is full of
handy number-tweaking methods ready and easy to use. 8ut most of them are , so we'll
start by learning what it means for a variable or method to be static, including constants in
1avastatic l|nol variables.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
274 chapter 10
Math methods
p([], jn ([ pz([ e]z,,
]n'( a, zny jn,(zne
vzjz] vz]a,. jn] eza,
([ ([], z ',(z(je',
ya ]n'( n] ( [zv zn
jn,(zne | pz([. j]] ya
n] j, ([ pz([ e]z,,.
MIH mc!he4s: zs r|esc zs yee||
cvcr ]c! !e z ]|e|z| mc!he4
Excci ihcic`s no glolal nr,L.r in ]ava. Bui ihinI aloui
ihis: whai il you havc a mcihou whosc lchavioi uocsn`i
uccnu on an insiancc vaiiallc valuc. TaIc ihc iounu)
mcihou in ihc Maih class, loi cxamlc. Ii uocs ihc samc
ihing cvciy iimc-iounus a uoaiing oini numlciihc
aigumcni io ihc mcihou) io ihc ncaicsi inicgci. Evciy
iimc. Il you hau 10,000 insianccs ol class Maih, anu ian
ihc iounu42.2) mcihou, you`u gci an inicgci valuc ol
42. Evciy iimc. In oihci woius, ihc mcihou acis on ihc
aigumcni, lui is ncvci allccicu ly an insiancc vaiiallc
siaic. Thc only valuc ihai changcs ihc way ihc iounu)
mcihou iuns is ihc aigumcni asscu io ihc mcihou!
Docsn`i ii sccm liIc a wasic ol cilccily goou hca sacc
io maIc an insiancc ol class Maih simly io iun ihc
iounu) mcihou. Anu whai aloui oLe. Maih mcihous
liIc min), which iaIcs iwo numciical iimiiivcs anu
iciuins ihc smallci ol ihc iwo. Oi max). Oi als), which
iciuins ihc alsoluic valuc ol a numlci.
These methods never use instonce voriobIe voIues. In laci ihc
Maih class uocsn`i Ln.e any insiancc vaiiallcs. So ihcic`s
noihing io lc gaincu ly maIing an insiancc ol class
Maih. So gucss whai. You uon`i havc io. As a maiici ol
laci, you can`i.
1: ----- :--: l.l l- M.l
:--:l--:l-- : -.-- -.l-' 1.l --.-: ]-- :.- N!/! :.] '---' -- l- M.l :|.:: l- -.- . --- M.l --:l
File Edit Window Help wasToldThereWouldBeNoMath
%javac TestMath
TestMath.java:3: Math() has private
access in java.lang.Math
Math mathObject = new Math();
^
1 error
Math mathObject = new Math();
f you try to make an instance of
class Math:
You'll get this error:
int x = Math.round(42.2);
int y = Math.min(56,12);
int z = Math.abs(-343);
1-:- --l-: ---- -:-
-:l.-:- .-.|-:, :- l--
-.-- --:-'l --- l-
--- .--l . :-:: --:l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 275
Ihc 4|ffcrcnrc |c! wccn rc]e|zr
|nen-s!z!|rI zn4 s!z!|r mc!he4s
]ava is ol|cci-oiicnicu, lui oncc in a whilc you havc a sccial casc,
iyically a uiiliiy mcihou liIc ihc Maih mcihous), whcic ihcic is
no nccu io havc an insiancc ol ihc class. Thc Icywoiu static lcis
a mcihou iun without ony instonce o[ the cIoss. A siaiic mcihou mcans
lchavioi noi uccnucni on an insiancc vaiiallc, so no insiancc/ol|cci
is icquiicu. ]usi ihc class."
PoIitik
CoIdpIoy
Song
s2.play();
s3.play();
c
.
||-
|.
]
|
`
-
-
l
:
-
-
-
-
-
-
:
-
-
||
:
.
-
:
-
|
-
|l
'
l
-
|.
]
c.||- |.]|` -- l:
------:- -|| :.-:-
M] w.]' l- |.]
My Wuy
Sex PisfoIs
Song
Son
g
o
b
j
e
c
f
public class Song {
String title;
public Song(String t) {
title = t;
}
public void play() {
SoundPlayer player = new SoundPlayer();
player.playSound(title);
}
public static int min(int a, int b){
//returns the lesser of a and b
}
r|r()
rax()
aos()
...
l|l|e
p|ay()
regular {non-static} method static method
1- :-----l .|-- - l- 'll|-'
-:l.-:- .-.|- : l- :-- l.l
|.]: --- ]-- :.|| |.]|`
N- -:l.-:- .-.|-:
1- --l- -.--
--:-'l :.-- -l
-:l.-:- .-.|- :l.l-
Math.min(42,36);
N
6 6B
)!
c
1
''
A
:-|-l-|] N
6 6B
)!
c
1
.-]---- - l: :l--- '
c:- l- c|.:: -.--, -.l--
l.- . ------:- .-.|-
-.--
l
-
-
-
:
l
.
-
:
-
:
-
:
|.
:
:
-
-
r|r()
rax()
aos()
...
Call a non-static method using a
reference variable name
Song t2 = new Song();
t2.play();
Whz! | ! mczns !e hzvc z
r|zss w| !h s!z!|r mc!he4s.
Olicn alihough noi always), a class wiih siaiic
mcihous is noi mcani io lc insianiiaicu. In Chaici
S wc ialIcu aloui alsiiaci classcs, anu how maiIing
a class wiih ihc abstract mouihci maIcs ii
imossillc loi anyonc io say ncw` on ihai class iyc.
In oihci woius, it`s impossibIe to instontiote on obstroct
cIoss.
Bui you can icsiiici oihci couc liom insianiiaiing
a ror-alsiiaci class ly maiIing ihc consiiucioi
private. Rcmcmlci, a eLoJ maiIcu iivaic mcans
ihai only couc liom wiihin ihc class can invoIc
ihc mcihou. A or.uo. maiIcu iivaic mcans
csscniially ihc samc ihing-only couc liom wiihin
ihc class can invoIc ihc consiiucioi. Nolouy can
say ncw` liom ou.Je ihc class. Thai`s how ii woiIs
wiih ihc Maih class, loi cxamlc. Thc consiiucioi
is iivaic, you cannoi maIc a ncw insiancc ol Maih.
Thc comilci Inows ihai youi couc uocsn`i havc
acccss io ihai iivaic consiiucioi.
This uocs ro mcan ihai a class wiih onc oi moic
siaiic mcihous shoulu ncvci lc insianiiaicu. In laci,
cvciy class you ui a main) mcihou in is a class wiih
a siaiic mcihou in ii!
Tyically, you maIc a main) mcihou so ihai you
can launch oi icsi anoihci class, ncaily always ly
insianiiaiing a class in main, anu ihcn invoIing a
mcihou on ihai ncw insiancc.
So you`ic licc io comlinc siaiic anu non-siaiic
mcihous in a class, alihough cvcn a singlc non-siaiic
mcihou mcans ihcic musi lc oe way io maIc an
insiancc ol ihc class. Thc only ways io gci a ncw
ol|cci aic ihiough ncw` oi ucsciializaiion oi
somcihing callcu ihc ]ava Rcucciion API ihai wc
uon`i go inio). No oihci way. Bui cxacily wLo says ncw
can lc an inicicsiing qucsiion, anu onc wc`ll looI ai
a liiilc laici in ihis chaici.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 277
8!z!|r mc!he4s rzn! esc nen-s!z!|r
||ns!znrcI vzr|z||cs|
Siaiic mcihous iun wiihoui Inowing aloui any aiiiculai
insiancc ol ihc siaiic mcihou`s class. Anu as you saw on
ihc icvious agcs, ihcic mighi noi cvcn be any insianccs
ol ihai class. Sincc a siaiic mcihou is callcu using ihc In
.ianuom)) as ooscu io an .rnre .ee.ere .lay)),
a siaiic mcihou can`i iclci io any insiancc vaiiallcs ol ihc
class. Thc siaiic mcihou uocsn`i Inow wL.L insiancc`s vaiiallc
valuc io usc.
]| ya (y ( a, zn
jn,(zne vzjz] |
jn,j] z ,(z(je ([],
([ ej] ([jn[,,
] ]n'( [nw w[je[
je(', jn,(zne vzjz]
ya' (z][jng za([
]| ya [zv (n ]ae[
je(, n ([ [z, z
,(z(je ([] ],n'(
[nw za( zny | ([.
public class Duck {
private int size;
public static void main (String[] args) {
System.out.println(Size of duck is + size);
}
public void setSize(int s) {
size = s;
}
public int getSize() {
return size;
}
}
f you try to compile this code:
I'm sure fhey're
foIking obouf MY
si;e voriobIe.
Mo, I'm preffy sure
fhey're foIking obouf
MY si;e voriobIe.
w
: l
-:
w
-:- :--
You'll get this error:
File Edit Window Help Quack
% javac Duck.java
Duck.java:6: non-static variable
size cannot be referenced from a
static context
System.out.println(Size
of duck is + size);
^
| l---': . l-: --
l- -. :-------, --
--'l --- .--l l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
static methods
278 chapter 10
8!z!|r mc!he4s rzn! esc nen-s!z!|r
mc!he4s, c| !hcr|
Whai uo non-siaiic mcihous uo. They usuoIIy use instonce
voriobIe stote to o[[ect the behovior o[ the method. A gciNamc)
mcihou iciuins ihc valuc ol ihc namc vaiiallc. Whosc namc.
Thc ol|cci uscu io invoIc ihc gciNamc) mcihou.
public class Duck {
private int size;
public static void main (String[] args) {
System.out.println(Size is + getSize());
}
public void setSize(int s) {
size = s;
}
public int getSize() {
return size;
}
}
This won't compile:
c.||- -l--|` -:l -:l---:
l- --l.|---l--|` -:-: l- :-- -:l.-:- .-.|-
File Edit Window Help Jack-in
% javac Duck.java
Duck.java:6: non-static method
getSize() cannot be referenced
from a static context
System.out.println(Size
of duck is + getSize());
^
B.: l- l- :.-- --|--
--:- :--
(-,- a,- |
oa|| qa--(:|-
What if you try to caII a non-static
method from a static method, but the
non-static method doesn't use any in-
stance variabIes. WiII the compiIer aIIow
that!
No. The compiler knows that
whether you do or do not use instance
variables in a non-static method, you con.
And think about the implications... if you
were allowed to compile a scenario like
that, then what happens if in the future
you want to change the implementation
of that non-static method so that one day
it Joes use an instance variableI Or worse,
what happens if a subclass ovett|Jes the
method and uses an instance variable in
the overriding versionI
I couId swear I've seen code that
caIIs a static method using a reference
variabIe instead of the cIass name.
ou con do that, but as your mother
always told you, "1ust because it's legal
doesn't mean it's good. Although it wotls
to call a static method using any instance
of the class, it makes for misleading (less-
readable) code. ou con say,
Duck d = new Duck();
String[] s = {};
d.main(s);
This code is legal, but the compiler |ust
resolves it back to the real class anyway
("OK, J is of type Duck, and main() is static,
so |'ll call the static main() in class Duck).
|n other words, using J to invoke main()
doesn't imply that main() will have any
special knowledge of the ob|ect that J is
referencing. |t's |ust an alternate woy to
invoke a static method, but the method is
still static!
DateFormat.getDateTimeInstance();
DateFormat.getTimeInstance();
NumberFormat.getPercentInstance();
M
.-
l
l:
koses ote teJ,
onJ lnown to oloom lote
5rnrics cnnr see
insrnnce vnrinble srnre
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 279
!.: l-: --:l .: l: ---
:-- .-.|-, -l l---': --|]
--- :-] - l- -:c---l
.-.|--l- --- - l- :|.::
8!z!|r vzr|z||c:
vz|ec |s !hc szmc fer II
|ns!znrcs ef !hc r|zss
Imaginc you wanicu io couni how many DucI
insianccs aic lcing cicaicu whilc youi iogiam is
iunning. How woulu you uo ii. Maylc an insiancc
vaiiallc ihai you incicmcni in ihc consiiucioi.
class Duck {
int duckCount = 0;
public Duck() {
duckCount++;
}
}
No, ihai woulun`i woiI lccausc uucICouni is an
insiancc vaiiallc, anu siaiis ai 0 loi cach DucI. You
coulu iiy calling a mcihou in somc oihci class, lui
ihai`s Iluugcy. You nccu a class ihai`s goi only a singlc
coy ol ihc vaiiallc, anu all insianccs shaic ihai onc
coy.
Thai`s whai a siaiic vaiiallc givcs you: a valuc shaicu
ly all insianccs ol a class. In oihci woius, onc valuc
ci , insicau ol onc valuc ci .
l: ---| .|-.]: :-l -:c---l l- | -.: l--
. l-: -.: -.-
public class Duck {
private int size;
private static int duckCount = 0;
public Duck() {
duckCount++;
}
public void setSize(int s) {
size = s;
}
public int getSize() {
return size;
}
}
N-- l -|| --
-:-----l- -.: l--
l- l-: :--:l--:l-- ---:,
-:.-:- -:c---l : :l.l:
.- ---'l - --:-l l- o
1
- :l.l: -:c
---l
.-.|- : -l.|-- 6
N
|
/
-
-- l- :|.:: : -:l
|-.-, N
6
1
-.: l-
- .
---
-:l.-:- : -
.-
A
l
-: --:l --:-'l -- l: --
- :-]
- -:c
---l
B
-:.-:- -:c
---l : :l.l:, l
-: --:l:
.|| :.-- . :-|- :-] - l /
-- :.- l-
- . :l.l: .-.|- .: . .-.|- l.l |-:
- . c
|
A
-:l-. - - .- --:l
D
u
c
k
ob
j
e
c
f
size: 1Z
duckCounf: 4
D
u
c
k
ob
j
e
c
f
size: ZZ
duckCounf: 4
D
u
c
k
ob
j
e
c
f
size:
duckCounf: 4
D
u
c
k
ob
j
e
c
f
size: Z0
duckCounf: 4
s|ze
slal|c duc|Courl
el3|ze()
sel3|ze()
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
280 chapter 10
Larlier in this chapter, we saw that a private
constructor means that the class can't be instantiated
from code running outside the class. |n other words,
only code from within the class can make a new
instance of a class with a private constructor. (There's
a kind of chicken-and-egg problem here. )
what if you want to write a class in such a way that
only ONL instance of it can be created, and anyone
who wants to use an instance of the class will always
use that one, single instanceI
Stati: va:ial|es a:e sha:eJ.
A|| iastaa:es aI the sae
:|ass sha:e a siag|e :ay aI
the stati: va:ial|es.
insfonce voriobIes: I per
sfofic voriobIes: I per
8f8l 88f00ll
-:l.-:- ---
-:l.-:- l--
:l.l: .-.|-
:-c--.-
static variabIes
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 281
|n| !|z||z|n] z s!z!|r vzr|z||c
Siaiic vaiiallcs aic iniiializcu whcn a In . IonJeJ. A class is
loaucu lccausc ihc ]VM ucciucs ii`s iimc io loau ii. Tyically,
ihc ]VM loaus a class lccausc somclouy`s iiying io maIc a
ncw insiancc ol ihc class, loi ihc hisi iimc, oi usc a siaiic
mcihou oi vaiiallc ol ihc class. As a iogiammci, you also
havc ihc oiion ol iclling ihc ]VM io loau a class, lui you`ic
noi liIcly io nccu io uo ihai. In ncaily all cascs, you`ic lciici
oll lciiing ihc ]VM ucciuc whcn io IonJ ihc class.
Anu ihcic aic iwo guaianiccs aloui siaiic iniiializaiion:
Siaiic vaiiallcs in a class aic iniiializcu lcloic any obe ol ihai
class can lc cicaicu.
Siaiic vaiiallcs in a class aic iniiializcu lcloic any n. eLoJ
ol ihc class iuns.
class Player {
static int playerCount = 0;
private String name;
public Player(String n) {
name = n;
playerCount++;
}
}
public class PlayerTestDrive {
public static void main(String[] args) {
System.out.println(Player.playerCount);
Player one = new Player(Tiger Woods);
System.out.println(Player.playerCount);
}
}
Siaiic vaiiallcs aic iniiializcu whcn ihc class is loaucu. Il you
uon`i cxliciily iniiializc a siaiic vaiiallc ly assigning ii a
valuc ai ihc iimc you ucclaic ii), ii gcis a uclauli valuc, so ini
vaiiallcs aic iniiializcu io zcio, which mcans wc uiun`i nccu
io cxliciily say layciCouni 0". Dcclaiing, lui noi iniiial-
izing, a siaiic vaiiallc mcans ihc siaiic vaiiallc will gci ihc uc-
lauli valuc loi ihai vaiiallc iyc, in cxacily ihc samc way ihai
insiancc vaiiallcs aic givcn uclauli valucs whcn ucclaicu.
All static variables
in a class are
initialized before
any ob]ect of
that class can be
created.
1- |.]--c---l : -l.|-- --- l- :|.:: : |-.-
w- -|:l|] -l.|-- l l- o, -l -- --'l ---
l- :-:- o : l- -.-|l .|-- -- -l: l.l: .-~
.|-: -l -.-|l .|--: -:l |- -:l.-:- .-.|-:
l-.-|l .|--: -- -:|.-- -l ---l.|--
:l.l: .- -:l.-:- .-.|-: .-- l- :.--
--l- -l---: ||--, :--l, -l:` o
--l- |-.l- --l: ||-.l, --|-` oo
--|-.- .|:-
--:l ------:-: --||
File Edit Window Help What?
% java PlayerTestDrive
0
1
---- .-] -:l.-:-: .-- -.-
.l-- .- --:l : :--.l-
A::-:: . :l.l: .-.|- -:l |- . :l.l:
--l---l l- :|.:: -.--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
282 chapter 10
s!z!|r f|nz| vzr|z||cs zrc rens!zn!s
A vaiiallc maiIcu nalmcans ihai-oncc iniiializcu-ii can
ncvci changc. In oihci woius, ihc valuc ol ihc siaiic hnal vaiiallc
will siay ihc samc as long as ihc class is loaucu. IooI u Maih.PI
in ihc API, anu you`ll hnu:
public static nal double PI = 3.141592653589793;
Thc vaiiallc is maiIcu public so ihai any couc can acccss ii.
Thc vaiiallc is maiIcu static so ihai you uon`i nccu an
insiancc ol class Maih which, icmcmlci, you`ic noi allowcu io
cicaic).
Thc vaiiallc is maiIcu nal lccausc PI uocsn`i changc as lai as
]ava is conccincu).
Thcic is no oihci way io ucsignaic a vaiiallc as a consiani, lui
ihcic is a naming convcniion ihai hcls you io iccognizc onc.
Constont voriobIe nomes shouId be in oII cops:
nitialize a hnal static variable:
At the time you decIure it:
1
public class Foo {
public static nal int FOO_X = 25;
}
In u stutic initiuIizer:
2
public class Bar {
public static nal double BAR_SIGN;
static {
BAR_SIGN = (double) Math.random();
}
}
OR
A static initiaIizer is a bIock
of code that runs when a
cIass is Ioaded, before any
other code can use the
cIass, so it's a great pIace
to initiaIize a static finaI
variabIe.
class Foo {
nal static int x;
static {
x = 42;
}
}
l: :-- ---: .: :--- .: l- :|.::
: |-.-, ---- .-] :l.l: --l-
: :.||- .- --- ---- .-] :l.l:
.-.|- :.- - -:-
--l:- l- -.-- :----l-- ~~ :l.l:
-.| .-.|-: .-- :--:l.-l:, :- l-
-.-- :--| - .|| ---:.:-, -l .-
----::--- :-.-.l- l- ---:
File Edit Window Help Jack-in
% javac Bar.java
Bar.java:1: variable BAR_SIGN
might not have been initialized
1 error
public class Bar {
public static nal double BAR_SIGN;
}
If you don't give u vuIue to u hnuI vuriubIe
in one of those two pIuces:
The compiIer wiII cutch it:
static finaI constants
-- -l.|-.l--'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
numbers and statics
you are here 283
A I iaa| va:ial|e eaas yaa
:aa't :haage its va|ae.
A I iaa| ethaJ eaas yaa
:aa't ave::iJe the ethaJ.
A I iaa| :|ass eaas yaa
:aa't exteaJ the :|ass li.e.
yaa :aa't a|e a sal:|assI.
non-static hnal variables
f|nz| |sn! jes! fer s!z!|r
vzr|z||cs...
You can usc ihc Icywoiu nal io mouily non-
siaiic vaiiallcs ioo, incluuing insiancc vaiiallcs,
local vaiiallcs, anu cvcn mcihou aiamcicis. In
cach casc, ii mcans ihc samc ihing: ihc valuc can`i
lc changcu. Bui you can also usc hnal io sio
somconc liom ovciiiuing a mcihou oi maIing a
sulclass.
class Foof {
nal int size = 3;
nal int whufe;
Foof() {
whufe = 42;
}
void doStuff(nal int x) {
// you can't change x
}
void doMore() {
nal int z = 7;
// you can't change z
}
}
hnal method
class Poof {
nal void calcWhufe() {
// important things
// that must never be overridden
}
}
hnal class
nal class MyMostPerfectClass {
// cannot be extended
}
If's oII so... so fnoI.
I meon, if I'd known
I wouIdn'f be obIe fo
chonge fhings...
--- ]-- :.-'l :.-- :--
--- ]-- :.-'l :.-- ---
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
284 chapter 10
(-,- a,- |
oa|| qa--(:|-
Um, there's something RALLY strange going on here. 1ust how many arguments I
pass! I mean, how many overIoaded format() methods are IN the String cIass! So, what happens
if I want to pass, say, ten different arguments to be formatted for a singIe output String!
Good catch. es, there |s something strange (or at least new and different) going on, and
no there are not a bunch of overloaded format() methods to take a different number of possible
arguments. |n order to support this new formatting (printf-like) AP| in 1ava, the language needed
another new featurevot|oole otument l|sts (called votots for short). we'll talk about varargs
only in the appendix because outside of formatting, you probably won't use them much in a well-
designed system.
format arguments
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 301
8e merh fer nem|crs, whz! z|ee! 4z!cs!
Imaginc you wani a Siiing ihai looIs liIc ihis: Sunuay, Nov 2S 2004"
Noihing sccial ihcic, you say. Wcll, imaginc ihai all you havc io siaii wiih is a vaiiallc
ol iyc Daic-A ]ava class ihai can icicscni a iimcsiam, anu now you wani io iaIc ihai
ol|cci as ooscu io a numlci) anu scnu ii ihiough ihc loimaiici.
Thc main uillcicncc lciwccn numlci anu uaic loimaiiing is ihai uaic loimais usc a
iwo-chaiacici iyc ihai siaiis wiih i" as ooscu io ihc singlc chaiacici l" oi u", loi
cxamlc). Thc cxamlcs lclow shoulu givc you a goou iuca ol how ii woiIs:
String.format(%tc, new Date());
Sun Nov 28 14:52:41 MST 2004
The complete date and time %tc
String.format(%tr, new Date());
03:01:47 PM
Just the time %tr
Date today = new Date();
String.format(%tA %tB %td,today,today,today);
Sunday, November 28
Day of the week, month and day %tA %tB %td
Date today = new Date();
String.format(%tA, %<tB %<td,today);
8ame as above, but without duplicating the arguments %tA %tB %td
Thcic isn`i a singlc loimai sccihci ihai will uo cxacily whai wc
wani, so wc havc io comlinc ihicc ol ihcm loi uay ol ihc wccI
%iA), monih %iB), anu uay ol ihc monih %iu).
B-l l.l --.-: -- .- l- .:: l- l.l- --:l - l--- l--:, --- -- -.: .-l - l-
---.l l.l -- -.-l |- -l--
---:, l- *lA -|| - -: -:l
l- .] - l- ---, -l l-- -- .- l- - l ..- l- -l -:l l- ---l .- ..- -- l-
.]- l- ---l
1- :---. : --l .-l - l- ---.ll- l':
-:l l- :.-.:l-- -- -.-l --l- .l-- l-
-:l -:--l- ---.ll- .-----l
1- .-|-~-.:-l ' : -:l .--l--
|. - l- :-:-- l.l l-||: l-
---.ll-- l- -:- l- ----: .-----l
..-' - l :.-: ]-- --- ---.l- l-
.-----l:, .- -:l-. ]-- ---.l l-
:.-- .-----l l--- ----l -.]:
/-- :.- l- - l: .: - - |- :.||- l---
----l -ll-- --l-: -- l- l.l- --:l, l-
-l l--- ----l -:-: - .l. --- l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
302 chapter 10
Werk|n] w| !h Pz!cs
You nccu io uo moic wiih uaics ihan |usi gci
oJn,` uaic. You nccu youi iogiams io au|usi
uaics, hnu clascu iimcs, iioiiiizc schcuulcs,
hccI, maIc schcuulcs. You nccu inuusiiial
siicngih uaic maniulaiion caaliliiics.
You coulu maIc youi own uaic iouiincs ol
couisc... anu uon`i loigci aloui lca ycais!)
Anu, ouch, ihosc occasional, csIy lca-
eorJ. Wow, ihis coulu gci comlicaicu. Thc
goou ncws is ihai ihc ]ava API is iich wiih
classcs ihai can hcl you maniulaic uaics.
Somciimcs ii lccls a liiilc oo iich...
Lef's see... how mony work
doys wiII fhere be if fhe
projecf sforfs on Feb Z7fh ond
ends on Augusf bfh7
manipuIating dates
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
numbers and statics
you are here 303
Mev|n] |zrkwzr4 zn4 ferwzr4 |n !|mc
Ici`s say youi comany`s woiI schcuulc is Monuay ihiough Iiiuay.
You`vc lccn assigncu ihc iasI ol hguiing oui ihc lasi woiI uay in
cach calcnuai monih ihis ycai...
Ia: a t:e-sta aI aav",
ase Pate. 5at Ia: eve:yth:ag
e|se, ase Ca|eaJa:.
t seems that ]ava.util.Date is actually... out of date
Eailici wc uscu |ava.uiil.Daic io hnu iouay`s uaic, so ii sccms
logical ihai ihis class woulu lc a goou lacc io siaii looIing loi
somc hanuy uaic maniulaiion caaliliiics, lui whcn you chccI
oui ihc API you`ll hnu ihai mosi ol Daic`s mcihous havc lccn
uciccaicu!
Thc Daic class is siill gicai loi gciiing a iimc siam"-an ol|cci
ihai icicscnis ihc cuiicni uaic anu iimc, so usc ii whcn you wani
io say, givc mc NOW".
Thc goou ncws is ihai ihc API iccommcnus java.util.Calcndar
insicau, so lci`s iaIc a looI:
Use ]ava.util.Calendar for your date manipulation
Thc ucsigncis ol ihc Calcnuai API wanicu io ihinI glolally,
liicially. Thc lasic iuca is ihai whcn you wani io woiI wiih uaics,
you asI loi a Calcnuai ihiough a siaiic mcihou ol ihc Calcnuai
class ihai you`ll scc on ihc ncxi agc), anu ihc ]VM hanus you lacI
an insiancc ol a concicic sulclass ol Calcnuai. Calcnuai is aciually
an alsiiaci class, so you`ic always woiIing wiih a concicic sulclass.)
Moic inicicsiing, ihough, is ihai ihc I.rJ ol calcnuai you gci
lacI will lc n.o..ne o. ,ou. IonIe. Much ol ihc woilu uscs ihc
Gicgoiian calcnuai, lui il you`ic in an aica ihai uocsn`i usc a
Gicgoiian calcnuai you can gci ]ava liliaiics io hanulc oihci
calcnuais such as Buuuhisi, oi Islamic oi ]aancsc.
Thc sianuaiu ]ava API shis wiih java.util.GrcgorianCalcndar, so
ihai`s whai wc`ll lc using hcic. Ioi ihc mosi aii, ihough, you
uon`i cvcn havc io ihinI aloui ihc Iinu ol Calcnuai sulclass you`ic
using, anu insicau locus only on ihc mcihous ol ihc Calcnuai class.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
304 chapter 10
0c!!|n] zn e|jcr! !hz! cr!cn4s 0z|cn4zr
How in ihc woilu uo you gci an insiancc" ol an alsiiaci class.
Wcll you uon`i ol couisc, ihis won`i woiI:
This WON'T work:
Calendar cal = new Calendar();
nstead, use the static getnstance{} method:
Calendar cal = Calendar.getInstance();
Woif o minufe.
If you con'f moke on
insfonce of fhe CoIendor
cIoss, whof exocfIy ore you
ossigning fo fhof CoIendor
reference7
You can't get an instance of Calendar,
but you can can get an instance of a
concrete Calendar subclass.
Olviously you can`i gci an insiancc ol Calcnuai, lccausc
Calcnuai is alsiiaci. Bui you`ic siill licc io call siaiic mcihous
on Calcnuai, sincc mcihous aic callcu on ihc ,
iaihci ihan on a aiiiculai insiancc. So you call ihc siaiic
gciInsiancc) on Calcnuai anu ii givcs you lacI... an insiancc
ol a concicic sulclass. Somcihing ihai cxicnus Calcnuai
which mcans ii can lc olymoihically assigncu io Calcnuai)
anu which-ly coniiaci-can icsonu io ihc mcihous ol class
Calcnuai.
In mosi ol ihc woilu, anu ly uclauli loi mosi vcisions ol ]ava,
you`ll lc gciiing lacI a java.util.GrcgorianCalcndar insiancc.
1- :--|-- ---'l .||-- l: '
1: :]-l. :--| |-- .-|.- .l l:
--l ~ --'-- --- . :l.l: --l-
getting a CaIendar
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 305
Werk|n] w| !h 0z|cn4zr e|jcr!s
Thcic aic scvcial Icy conccis you`ll nccu io unucisianu in
oiuci io woiI wiih Calcnuai ol|ccis:
Ficlds hold stote - A Calcnuai ol|cci has many hclus ihai aic uscu io
icicscni asccis ol iis uliimaic siaic, iis uaic anu iimc. Ioi insiancc, you
can gci anu sci a Calcnuai`s ,en. oi orL.
Datcs and Timcs can bc incremented - Thc Calcnuai class has mcihous ihai
allow you io auu anu suliiaci valucs liom vaiious hclus, loi cxamlc auu
onc io ihc monih", oi suliiaci ihicc ycais".
Datcs and Timcs can bc rcprcscntcd in miIIiseconds - Thc Calcnuai class
lcis you convcii youi uaics inio anu oui ol a milliscconu icicscniaiion.
Sccihcally, ihc numlci ol milliscconus ihai havc occuicu sincc ]anuaiy
1si, 1970.) This allows you io ciloim iccisc calculaiions such as clascu
iimc lciwccn iwo iimcs" oi auu 6S houis anu 2S minuics anu 12 scconus
io ihis iimc".
An example of working with a Calendar ob]ect:
Calendar c = Calendar.getInstance();
c.set(2004,0,7,15,40);
long day1 = c.getTimeInMillis();
day1 += 1000 * 60 * 60;
c.setTimeInMillis(day1);
System.out.println(new hour + c.get(c.HOUR_OF_DAY));
c.add(c.DATE, 35);
System.out.println(add 35 days + c.getTime());
c.roll(c.DATE, 35);
System.out.println(roll 35 days + c.getTime());
c.set(c.DATE, 1);
System.out.println(set to 1 + c.getTime());
File Edit Window Help Time-Flies
new hour 16
add 35 days Wed Feb 11 16:40:41 MST 2004
roll 35 days Tue Feb 17 16:40:41 MST 2004
set to 1 Sun Feb 01 16:40:41 MST 2004
c----l l: l- . -|'
.----l - -||:-:--:
-l l-- l- ).- 7, ioo+
.l |-+
o
|N-l:- l- ---l : ----~.:-`
A ?- .]: l- l- .l-, -:
:--| --- -: -l- |---.-]
-||' ?- .]: --l- l: .l- 1:
--||:' l- .l- .-. ?- .]:, -l
l6! N61 :.-- l- ---l'
w-'-- --l -:-----l- ---, -:l
-- . :-l' - l- .l-
A .- ---': ---l - -||:, l-- -.l- l- l--
|N-l:- l- +=', l': |- .]| = .]| + `
1: --l-l :----: -- -||:,
., --||, .- :-l ---
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
306 chapter 10
H|]h||]h!s ef !hc 0z|cn4zr ||
Wc |usi woiIcu ihiough using a lcw ol ihc hclus anu
mcihous in ihc Calcnuai class. This is a lig API, so
wc`ic showing only a lcw ol ihc mosi common hclus
anu mcihous ihai you`ll usc. Oncc you gci a lcw ol
ihcsc ii shoulu lc iciiy casy io lcnu ihc icsi ol ihc
ihis API io youi will.
key CaIendar Methods
add(int eId, int amount)
get(int eId)
getInstance()
get7imeInMiIIis()
roII(int eId, booIean up)
set(int eId, int vaIue)
set(year, month, day, hour, minute) (aII ints)
set7imeInMiIIis(Iong miIIis)
// more...
Adds or subtracts time from the calendar's field.
Peturns the value of the given calendar field.
Peturns this Calendar's time in millis, as a long.
Adds or subtracts time without changing larger fields.
Sets the value of a given Calendar field.
A common variety of set to set a complete time.
Sets a Calendar's time based on a long milli-time.
Peturns a Calendar, you can specify a locale.
key CaIendar FieIds
DA7 / DAY_DF_MDN7H
HDUR / HDUR _DF_DAY
MILLISCDND
MINU7
MDN7H
YAR
ZDN_DFFS7
// more...
Get / set the day of month
Get / set the l2 hour or 24 hour value.
Get / set the minute.
Get / set the month.
Get / set the year.
Get / set raw offset of GMT in millis.
Get / set the milliseconds.
CaIendar API
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 307
Ivcn merc 8!z!|rs|... s!z!|r |mper!s
Ncw io ]ava .0... a ical mixcu llcssing. Somc colc lovc
ihis iuca, somc colc haic ii. Siaiic imoiis cxisi only io savc
you somc iying. Il you haic io iyc, you mighi |usi liIc ihis
lcaiuic. Thc uownsiuc io siaiic imoiis is ihai - il you`ic noi
caiclul - using ihcm can maIc youi couc a loi haiuci io icau.
Thc lasic iuca is ihai whcncvci you`ic using a siaiic class, a
siaiic vaiiallc, oi an cnum moic on ihosc laici), you can
imoii ihcm, anu savc youiscll somc iying.
8ome old-fashioned code:
import java.lang.Math;
class NoStatic {
public static void main(String [] args) {
System.out.println(sqrt + Math.sqrt(2.0));
System.out.println(tan + Math.tan(60));
}
}
8ame code, with static imports:
import static java.lang.System.out;
import static java.lang.Math.*;
class WithStatic {
public static void main(String [] args) {
out.println(sqrt + sqrt(2.0));
out.println(tan + tan(60));
}
}
ll you're or|y o|r lo use a slal|c reroer
a leW l|res, We l||r| you s|ou|d avo|d
slal|c |rporls, lo |e|p |eep l|e code rore
readao|e.
ll you're o|r lo use a slal|c reroer a |ol,
(|||e do|r |ols ol Val| ca|cu|al|ors), l|er
|l's prooao|y 0K lo use l|e slal|c |rporl.
Nol|ce l|al you car use W||dcards (.), |r
your slal|c |rporl dec|aral|or.
A o| |ssue W|l| slal|c |rporls |s l|al |l's
rol loo |ard lo creale rar|r corl||cls For
exarp|e, |l you |ave lWo d|llererl c|asses
W|l| ar 'add() rel|od, |oW W||| you ard
l|e corp||er |roW W||c| ore lo use?
6uveuIs & 6eIthus
1
- :]-l
.
l
- -:- -
--
-:|.-- :l
.l
: -
--l
:
l.l: ---l: - .:l--
lse Ca:eIa||y
stat:: :a:ts :aa
a|e yaa: :aJe
:aaIas:ag ta :eaJ
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
308 chapter 10
Instance Variable
I uon`i cvcn Inow why wc`ic uoing ihis.
Evciyonc Inows siaiic vaiiallcs aic |usi uscu
loi consianis. Anu how many ol ihosc aic
ihcic. I ihinI ihc wholc API musi havc, whai,
loui. Anu ii`s noi liIc anylouy cvci uscs
ihcm.
Iull ol ii. Ycah, you can say ihai again. OK,
so ihcic aic a lcw in ihc Swing liliaiy, lui
cvciylouy Inows Swing is |usi a sccial casc.
OI, lui lcsiucs a lcw GUI ihings, givc mc an
cxamlc ol |usi onc siaiic vaiiallc ihai anyonc
woulu aciually usc. In ihc ical woilu.
Wcll, ihai`s anoihci sccial casc. Anu nolouy
uscs ihai cxcci loi uclugging anyway.
8tatic Variable
You ically shoulu chccI youi lacis. Whcn
was ihc lasi iimc you looIcu ai ihc API. Ii`s
liicIin` loaucu wiih siaiics! Ii cvcn has cniiic
classcs ucuicaicu io holuing consiani valucs.
Thcic`s a class callcu SwingConsianis, loi
cxamlc, ihai`s |usi lull ol ihcm.
Ii mighi lc a sccial casc, lui ii`s a ically
imoiiani onc! Anu whai aloui ihc Coloi
class. Whai a ain il you hau io icmcmlci ihc
RGB valucs io maIc ihc sianuaiu colois. Bui
ihc coloi class alicauy has consianis uchncu
loi lluc, uilc, whiic, icu, cic. Vciy hanuy.
How`s Sysicm.oui loi siaiicis. Thc oui in
Sysicm.oui is a siaiic vaiiallc ol ihc Sysicm
class. You cisonally uon`i maIc a ncw
insiancc ol ihc Sysicm, you |usi asI ihc Sysicm
class loi iis oui vaiiallc.
Oh, liIc uclugging isn`i imoiiani.
Anu hcic`s somcihing ihai iolally ncvci
ciosscu youi naiiow minu-lci`s lacc ii, siaiic
vaiiallcs aic moic clhcicni. Onc ci class
insicau ol onc ci insiancc. Thc mcmoiy
savings mighi lc hugc!
1cnih|`s 1alk: An instance variable
takes cheap shets at a static variable
static vs. instance
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 309
Um, aicn`i you loigciiing somcihing.
Siaiic vaiiallcs aic aloui as un-OO as ii gcis!!
Gcc why noi |usi go iaIc a giani lacIwaius
sic anu uo somc ioccuuial iogiamming
whilc wc`ic ai ii.
You`ic liIc a glolal vaiiallc, anu any
iogiammci woiih his PDA Inows ihai`s
usually a Bau Thing.
Ycah you livc in a class, lui ihcy uon`i call
ii CIn-Oiicnicu iogiamming. Thai`s |usi
siuiu. You`ic a iclic. Somcihing io hcl ihc
olu-iimcis maIc ihc lca io |ava.
Wcll, OK, cvciy oncc in a whilc suic, ii maIcs
scnsc io usc a siaiic, lui lci mc icll you, alusc
ol siaiic vaiiallcs anu mcihous) is ihc maiI
ol an immaiuic OO iogiammci. A ucsignci
shoulu lc ihinIing aloui obe siaic, noi In
siaic.
Siaiic mcihous aic ihc woisi ihings ol all,
lccausc ii usually mcans ihc iogiammci is
ihinIing ioccuuially insicau ol aloui ol|ccis
uoing ihings lascu on ihcii uniquc ol|cci
siaic.
Riiiiiighi. Whaicvci you nccu io icll youiscll...
Whai.
Whai uo you mcan ur-OO.
I am NOT a glolal vaiiallc. Thcic`s no such
ihing. I livc in a class! Thai`s iciiy OO you
Inow, a CIASS. I`m noi |usi siiiing oui ihcic
in sacc somcwhcic, I`m a naiuial aii ol ihc
siaic ol an ol|cci, ihc only uillcicncc is ihai
I`m shaicu ly all insianccs ol a class. Vciy
clhcicni.
Aliighi |usi sio iighi ihcic. THAT is
uchniicly noi iiuc. Somc siaiic vaiiallcs aic
alsoluicly ciucial io a sysicm. Anu cvcn ihc
oncs ihai aicn`i ciucial suic aic hanuy.
Why uo you say ihai. Anu whai`s wiong wiih
siaiic mcihous.
Suic, I Inow ihai ol|ccis shoulu lc ihc locus
ol an OO ucsign, lui |usi lccausc ihcic aic
somc cluclcss iogiammcis oui ihcic... uon`i
ihiow ihc laly oui wiih ihc lyiccouc. Thcic`s
a iimc anu lacc loi siaiics, anu whcn you
nccu onc, noihing clsc lcais ii.
1nstance VarIabIe StatIc VarIabIe
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
310 chapter 10
] ge eomgj|e;
[[ ]zvz |j] n ([j, zg ,n(, z
e]( gz. (a j j, ( ]zy
ej] zn] ](jn w[([ ([j,
|j] wj]] ej]. ]| j( wn'( ej],
[w wa]] ya |jy j(, zn]
j| j( ], ej], w[z(
wa]] j(, a(a(/
class StaticSuper{
static {
System.out.println{"super static block"|,
}
StaticSuper{
System.out.println{
"super constructor"|,
}
}
public class StaticTests extends StaticSuper {
static int rand,
static {
rand = {int| {Math.random{| * 6|,
System.out.println{"static block " + rand|,
}
StaticTests{| {
System.out.println{"constructor"|,
}
public static void main{String args| {
System.out.println{"in main"|,
StaticTests st = new StaticTests{|,
}
}
File Edit Window Help Cling
%java StaticTests
static block 4
in main
super static block
super constructor
constructor
PossibIe Dutput
File Edit Window Help Electricity
%java StaticTests
super static block
static block 3
in main
super constructor
constructor
PossibIe Dutput
|f it compiles, which of these is
the outputI
be the compiIer
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
numbers and statics
you are here 311
This chapter explored the wonderful, static, world
of 1ava. our |ob is to decide whether each of the
following statements is true or false.
1. To usc ihc Maih class, ihc hisi sic is io maIc an insiancc ol ii.
2. You can maiI a consiiucioi wiih ihc Icywoiu.
S. Siaiic mcihous uon`i havc acccss io insiancc vaiiallc siaic ol ihc ihis` ol|cci.
4. Ii is goou iaciicc io call a siaiic mcihou using a iclcicncc vaiiallc.
. Siaiic vaiiallcs coulu lc uscu io couni ihc insianccs ol a class.
6. Consiiuciois aic callcu lcloic siaiic vaiiallcs aic iniiializcu.
7. MAX_SIZE woulu lc a goou namc loi a siaiic hnal vaiiallc.
S. A siaiic iniiializci llocI iuns lcloic a class`s consiiucioi iuns.
9. Il a class is maiIcu hnal, all ol iis mcihous musi lc maiIcu hnal.
10. A hnal mcihou can only lc ovciiiuucn il iis class is cxicnucu.
11. Thcic is no wiaci class loi loolcan iimiiivcs.
12. A wiaci is uscu whcn you wani io iicai a iimiiivc liIc an ol|cci.
1S. Thc aiscXxx mcihous always iciuin a Siiing.
14. Ioimaiiing classcs which aic uccoulcu liom I/O), aic in ihc |ava.loimai
acIagc.
fs-s cs |s.ss
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
312 chapter 10
This one might actually be useful! |n addition to what you've learned in the last few
pages about manipulating dates, you'll need a little more information... Pirst, full
moons happen every 29.52 days or so. Second, there was a full moon on 1an. 7th,
2004. our |ob is to reconstruct the code snippets to make a working 1ava program
that produces the output listed below (plus more full moon dates). (ou might not
need all of the magnets, and add all the curly braces you need.) Oh, by the way, your
output will be different if you don't live in the mountain time zone.
File Edit Window Help Howl
% java FullMoons
full moon on Fri Feb 06 04:09:35 MST 2004
full moon on Sat Mar 06 16:38:23 MST 2004
full moon on Mon Apr 05 06:07:11 MDT 2004
Iaaa: CaJe Kagaets
static import java.lang.System.out;
import java.util.*;
println
import static java.lang.System.out;
(full moon on %tc, c));
(c.format
(full moon on %t, c));
(String.format
Calendar c = Calendar.getInstance();
public static void main(String [] args) {
import ava.io.*,
out.println
class FullMoons {
c.setTimeInMillis(day1);
static int DAY_IM = 1000 * 60 * 60 * 24;
static int DAY_IM = 60 * 60 * 24;
for (int x = 0; x < 60; x++) {
long day1 = c.getTimeInMillis();
c.set(2004,1,7,15,40);
c.set(2004,0,7,15,40);
day1 += (DAY_IM * 29.52);
Calendar c = new Calendar();
code magnets
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
numbers and statics
you are here 313
]e;ejze o|ajoz
StaticSuper{ } {
System.out.println{
"super constructor"|,
}
File Edit Window Help Cling
%java StaticTests
super static block
static block 3
in main
super constructor
constructor
PossibIe Dutput
] ge eomgj|e;
SfoficSuper is o consfrucfor, ond musf
hove ( ) in ifs signofure. Mofice fhof os
fhe oufpuf beIow demonsfrofes, fhe sfofic
bIocks for bofh cIosses run before eifher
of fhe consfrucfors run.
1. To usc ihc Maih class, ihc hisi sic is io
maIc an insiancc ol ii.
2. You can maiI a consiiucioi wiih ihc Icy-
woiu siaiic`.
S. Siaiic mcihous uon`i havc acccss io an
ol|cci`s insiancc vaiiallcs.
4. Ii is goou iaciicc io call a siaiic mcihou
using a iclcicncc vaiiallc.
. Siaiic vaiiallcs coulu lc uscu io couni ihc
insianccs ol a class.
6. Consiiuciois aic callcu lcloic siaiic vaii-
allcs aic iniiializcu.
7. MAX_SIZE woulu lc a goou namc loi a
siaiic hnal vaiiallc.
S. A siaiic iniiializci llocI iuns lcloic a class`s
consiiucioi iuns.
9. Il a class is maiIcu hnal, all ol iis mcihous
musi lc maiIcu hnal.
10. A hnal mcihou can only lc ovciiiuucn il
iis class is cxicnucu.
11. Thcic is no wiaci class loi loolcan
iimiiivcs.
12. A wiaci is uscu whcn you wani io iicai a
iimiiivc liIc an ol|cci.
1S. Thc aiscXxx mcihous always iciuin a
Siiing.
14. Ioimaiiing classcs which aic uccoulcu
liom I/O), aic in ihc |ava.loimai acIagc.
FuIse
FuIse
True
FuIse
True
FuIse
True
True
FuIse
FuIse
FuIse
True
FuIse
FuIse
True or FoIse
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
314 chapter 10
]e;ejze o|ajoz
import java.util.*;
import static java.lang.System.out;
class FullMoons {
static int DAY_IM = 1000 * 60 * 60 * 24;
public static void main(String [] args) {
Calendar c = Calendar.getInstance();
c.set(2004,0,7,15,40);
long day1 = c.getTimeInMillis();
for (int x = 0; x < 60; x++) {
day1 += (DAY_IM * 29.52)
c.setTimeInMillis(day1);
out.println(String.format(full moon on %tc, c));
}
}
}
File Edit Window Help Howl
% java FullMoons
full moon on Fri Feb 06 04:09:35 MST 2004
full moon on Sat Mar 06 16:38:23 MST 2004
full moon on Mon Apr 05 06:07:11 MDT 2004
Noics on ihc Iunai Couc Magnci:
You mighi uiscovci ihai a lcw ol ihc
uaics iouuccu ly ihis iogiam aic
oll ly a uay. This asiionomical siull
is a liiilc iiicIy, anu il wc mauc ii
cilcci, ii woulu lc ioo comlcx io
maIc an cxcicisc hcic.
Hini: onc iollcm you mighi iiy io
solvc is lascu on uillcicnccs in iimc
zoncs. Can you soi ihc issuc.
code magnets soIution
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
11 exception handIing
this is a new chapter 315
Stuff happens. The fiIe isn't there. The server is down. No matter how
good a programmer you are, you can't control everything. Things can go wrong. vety wrong.
when you write a risky method, you need code to handle the bad things that might happen.
8ut how do you lnow when a method is riskyI And where do you put the code to honJle the
exceriennl situationI So far in this book, we haven't teolly taken any risks. we've certainly had
things go wrong at runtime, but the problems were mostly flaws in our own code. 8ugs. And
those we should fix at development time. No, the problem-handling code we're talking about
here is for code that you cont guaranatee will work at runtime. Code that expects the file to be
in the right directory, the server to be running, or the Thread to stay asleep. And we have to do
this now. 8ecause in th|s chapter, we're going to build something that uses the risky 1avaSound
AP|. we're going to build a M|D| Music Player.
Risky Behavior
Sure if's risky,
buf I con if if
somefhing goes wrong.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
31
chapter 11
buiIding the MIDI Music PIayer
Ic!s mzkc z Mes|r Mzrh|nc
Ovci ihc ncxi ihicc chaicis, wc`ll luilu a lcw uillcicni sounu
alicaiions, incluuing a BcaiBox Dium Machinc. In laci,
lcloic ihc looI is uonc, wc`ll havc a mulii-layci vcision so
you can scnu youi uium loos io anoihci layci, Iinu ol liIc
a chai ioom. You`ic going io wiiic ihc wholc ihing, alihough
you can choosc io usc Rcauy-laIc couc loi ihc GUI aiis.
OK, so noi cvciy IT ucaiimcni is looIing loi a ncw BcaiBox
scivci, lui wc`ic uoing ihis io Ien.r moic aloui Jn.n. Builuing
a BcaiBox is |usi a way io havc lun wL.Ie wc`ic lcaining ]ava.
Ihc f|n|shc4 Bcz!Ber |eeks semc!h|n] ||kc !h|s:
]--- --::.-, l.l -l:
:--l l- l- -l-- |.]--:,
.|-- -l ]--- :-----l
-.l .ll---, --- ]--
l --|l'
Andy: groove #2
6hr|s: groove2 rev|sed
N|ge|: dance beat
dance beat
-:--- --::.-: --- -l-- |.]--: c|: --- l- |-. l- .ll--- l.l
--: -l l, .- l-- :|:
'l.-l' l- |.] l
Pui chccImaiIs in ihc loxcs loi cach ol ihc 16 lcais`. Ioi cxamlc, on lcai
1 ol 16) ihc Bass uium anu ihc Maiacas will lay, on lcai 2 noihing, anu
on lcai S ihc Maiacas anu Closcu Hi-Hai... you gci ihc iuca. Whcn you hii
Siaii`, ii lays youi aiicin in a loo uniil you hii Sio`. Ai any iimc, you
can caiuic" onc ol youi own aiicins ly scnuing ii io ihc BcaiBox scivci
which mcans any oihci laycis can lisicn io ii). You can also loau any ol ihc
incoming aiicins ly clicIing on ihc mcssagc ihai gocs wiih ii.
/-- -.- . -.l- |-- |. ||~-.l --- .ll---`
] -ll- :-:-.-: - l- --:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
317
Wc|| s!zr! w| !h !hc |zs|rs
M
|l
| |- .: ----
.l--
.--l -- . :-- :--| -
|.]-, -l l --:-'l .- .-]
.:l-.| :--- .l. |l': - -
|- :--l -
-:: -:l--:l--:
-- . |.]--~.--
M|l| |-
M
|l
|~
:..
|- |-:l
---
--l
Olviously wc`vc goi a lcw ihings io lcain lcloic ihc wholc
iogiam is hnishcu, incluuing how io luilu a Swing GUI, how
io orre io anoihci machinc via nciwoiIing, anu a liiilc I/O
so wc can erJ somcihing io ihc oihci machinc.
Oh ycah, anu ihc ]avaSounu API. TLn` whcic wc`ll siaii in ihis
chaici. Ioi now, you can loigci ihc GUI, loigci ihc nciwoiIing
anu ihc I/O, anu locus only on gciiing somc MIDI-gcnciaicu
sounu io comc oui ol youi comuici. Anu uon`i woiiy il you
uon`i Inow a ihing aloui MIDI, oi a ihing aloui icauing oi
maIing music. Evciyihing you nccu io lcain is covcicu hcic.
You can almosi smcll ihc iccoiu ucal.
Ihc 1zvz8een4 ||
]avaSounu is a collcciion ol classcs anu inicilaccs auucu io
]ava siaiiing wiih vcision 1.S. Thcsc aicn`i sccial auu-ons,
ihcy`ic aii ol ihc sianuaiu ]2SE class liliaiy. ]avaSounu is slii
inio iwo aiis: MIDI anu Samlcu. Wc usc only MIDI in ihis
looI. MIDI sianus loi Musical Insiiumcni Digiial Inicilacc,
anu is a sianuaiu ioiocol loi gciiing uillcicni Iinus ol
clcciionic sounu cquimcni io communicaic. Bui loi
oui BcaiBox a, you can ihinI ol MIDI as n I.rJ o
Lee u. ihai you lccu inio somc ucvicc you can ihinI
ol liIc a high-icch layci iano`. In oihci woius, MIDI
uaia uocsn`i aciually incluuc any ourJ, lui ii uocs
incluuc ihc .r.u.or ihai a MIDI-icauing insiiumcni
can lay lacI. Oi loi anoihci analogy, you can ihinI ol
a MIDI hlc liIc an HTMI uocumcni, anu ihc insiiumcni
ihai icnucis ihc MIDI hlc i.c. In, ii) is liIc ihc Wcl
liowsci.
MIDI uaia says wLn io uo lay miuulc C, anu hcic`s how haiu
io hii ii, anu hcic`s how long io holu ii, cic.) lui ii uocsn`i say
anyihing ai all aloui ihc aciual ourJ you hcai. MIDI uocsn`i
Inow how io maIc a uuic, iano, oi ]immy Hcnuiix guiiai
sounu. Ioi ihc aciual sounu, wc nccu an insiiumcni a MIDI
ucvicc) ihai can icau anu lay a MIDI hlc. Bui ihc ucvicc is
usually moic liIc an er..e bnrJ o. o.Le.n ol insiiumcnis. Anu
ihai insiiumcni mighi lc a hysical ucvicc, liIc ihc clcciionic
Icyloaiu synihcsizcis ihc iocI musicians lay, oi ii coulu
cvcn lc an insiiumcni luili cniiicly in soliwaic, living in youi
comuici.
Ioi oui BcaiBox, wc usc only ihc luili-in, soliwaic-only
insiiumcni ihai you gci wiih ]ava. Ii`s callcu a ,rLe..e. somc
lolIs iclci io ii as a own.e ,rL) lccausc ii .ene sounu.
Sounu ihai you Len..
-.--
M|l| -:- ---: -- l-
'--.' . M|l| |- .- |.] .:
l- :--- 1- -:- -l
- . :]-l-:--- -]-.- --
:--- -l-- - - -:l-----l
c:-.||], . M|l| -:l-----l
:.- |.] . |61 - ----l
:---: |.--, ---:, -|-,
-l:`, .- .|| .l l- :.-- l--
- . M|l| |- :-'l |- :--l
--:: -- -:l --- --::.- -
l- .- ~~ l :.- -| l-
.-l: -- A|| l- --::.-:
|.]- . .-l:-|.- :--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
chapter 11
I|rs! wc ncc4 z 8cecnrcr
Bcloic wc can gci any sounu io lay, wc nccu a Scqucncci ol|cci. Thc
scqucncci is ihc ol|cci ihai iaIcs all ihc MIDI uaia anu scnus ii io ihc iighi
insiiumcnis. Ii`s ihc ihing ihai ihc music. A scqucncci can uo a loi ol
uillcicni ihings, lui in ihis looI, wc`ic using ii siiicily as a laylacI ucvicc. IiIc
a CD-layci on youi sicico, lui wiih a lcw auucu lcaiuics. Thc Scqucncci class
is in ihc |avax.sounu.miui acIagc aii ol ihc sianuaiu ]ava liliaiy as ol vcision
1.S). So lci`s siaii ly maIing suic wc can maIc oi gci) a Scqucncci ol|cci.
but it Iooked so simpIe
import javax.sound.midi.*;
public class MusicTest1 {
public void play() {
Sequencer sequencer = MidiSystem.getSequencer();
System.out.println(We got a sequencer);
} // close play
public static void main(String[] args) {
MusicTest1 mt = new MusicTest1();
mt.play();
} // close main
} // close class
---l l- ..:---- .:.-
w- --- . ----:-- --:l |l': l-
-.- .-l - l- M|l| -:-/-:l-----l
--'-- -:- |l': l- l- l.l, --||,
:----:-: .|| l- M|l| ----.l-- -l-
. ':--' B-l -- --'l -.- . -.-
--- --- ---:-|-: ~~ -- .- l- .: l-
M]:l-- l- - -: ---
File Edit Window Help SayWhat?
% javac MusicTest1.java
MusicTest1.java:13: unreported exception javax.sound.midi.
MidiUnavailableException; must be caught or declared to be
thrown
Sequencer sequencer = MidiSystem.getSequencer();
^
1 errors
1: :-- ---'l :--|-' 1- :--|-- :.]: l---': .-
'------l- -:-l--' l.l --:l - :.-l -- -:|.--
8emc!h|n]s wren]|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
319
1 Let's say you want
to call a method in a
class that you didn't
write.
2 That method does
something risky,
something that might
not work at runtime.
3 You need to know
that the method
you're calling is
risky.
Whz! hzppcns whcn z mc!he4 yee wzn! !e rz||
|pre|z||y |n z r|zss yee 4|4n! wr| !cI |s r|sky!
4 You then write code
that can handle the
failure if it does
happen. You need to be
prepared, ]ust in case.
you
cIoss you
didn'f wrife
wrife
f
h
o
f
uses mefh
o
d
s
i
n
void moo() {
if (serverDown) {
explode();
}
}
you
your code
class Cow {
void moo() {
if (serverDown){
explode();
}
}
}
cIoss you
didn'f wrife
class Cow {
void moo() {
if (serverDown){
explode();
}
}
}
cIoss you
didn'f wrife
class Cow {
void moo() {
if (serverDown){
explode();
}
}
}
I wonder if
fhof mefhod
couId bIow up...
My moo()
mefhod wiII
expIode if fhe
server is down.
you
w
rife so
f
e
I
y
Mow fhof I
know, I con foke
precoufions.
your code
class Bar {
void go() {
moo();
}
int stuff() {
x.beep();
}
}
class Bar {
void go() {
try{
moo();
}catch(MX m){
cry();
}
}
}
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
chapter 11
1- A|| -:: l-|| ]--
l.l -l----:--|`
:.- l--- .- -:-l--
Mc-..|.|-!:-l--
A --l- .: l- -:|.--
l- -:-l--: l -l
l---
1: .-l l-||: ]-- w+!N ]-- -l -l l.l
-:-l-- ~~ - l: :.:-, -:.-:- - --:---:-
--:l-:l--: |-: :--| -:l --.-: l- :----:--
: .|--.] -- -:-`
]ava`s cxcciion-hanuling mcchanism is a clcan, wcll-lighicu way io hanulc cxcciional
siiuaiions" ihai o u ai iuniimc, ii lcis you ui all youi ciioi-hanuling couc in onc
casy-io-icau lacc. Ii`s lascu on you Irow.r ihai ihc mcihou you`ic calling is iisIy
i.c. ihai ihc mcihou .L gcnciaic an cxcciion), so ihai you can wiiic couc io ucal
wiih ihai ossililiiy. Il you Irow you mighi gci an cxcciion whcn you call a aiiiculai
mcihou, you can lc .en.eJ loi-ossilly cvcn .eo.e. liom-ihc iollcm ihai causcu
ihc cxcciion.
So, how Jo you Inow il a mcihou ihiows an cxcciion. You hnu a throws clausc in ihc
iisIy mcihou`s ucclaiaiion.
The getSequencer() method takes a risk. t can fail at runtime.
8o it must declare' the risk you take when you call it.
when things might go wrong
Mc!he4s |n 1zvz esc ex6ef|o0t !e !c|| !hc rz|||n] re4c,
8emc!h|n] Bz4 Hzppcnc4. | fz||c4.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
321
Ihc remp||cr ncc4s !e knew
!hz! Y00 knew yeerc rz|||n]
z r|sky mc!he4.
Il you wia ihc iisIy couc in somcihing callcu a
, ihc comilci will iclax.
A iiy/caich llocI iclls ihc comilci ihai you
an cxcciional ihing coulu hacn in ihc
mcihou you`ic calling, anu ihai you`ic icaicu
io hanulc ii. Thai comilci uocsn`i caic you
hanulc ii, ii caics only ihai you say you`ic iaIing
caic ol ii.
import javax.sound.midi.*;
public class MusicTest1 {
public void play() {
try {
Sequencer sequencer = MidiSystem. getSequencer();
System.out.println(Successfully got a sequencer);
} catch(MidiUnavailableException ex) {
System.out.println(Bummer);
}
} // close play
public static void main(String[] args) {
MusicTest1 mt = new MusicTest1();
mt.play();
} // close main
} // close class
-l l- -:] l-
- . 'l-]' |-:
-
.- . ':.l:' |-:
-- -
.l l-
-
l- -
:-l--.| :l-.l--
.--: ~
~
- -l-- -
--
:, .
M
c
-..|.|-!
:-l-- : l---
-
] l- :.|| l- -l
----:--|`
;
~.
.
..
/.
.
~/., ~ ./ ..
~. , ./ .
~ ~
~
,.~. ,/, .
~//
;
~. ,/,.
. .~, . ~
~/ ./ .
,
, . .~
., ~. ./ . . .~
.
~., ..
. ~ .~/
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
322
chapter 11
I'm gonno
fhis risky fhing
ond I'm gonno
myseIf if I foII.
Don't try this at home.
try {
// do risky thing
} catch(Exception ex) {
// try to recover
}
n crrcp!|en |s zn e|jcr!...
ef !ypc Irrcp!|en.
Which is loiiunaic, lccausc ii woulu lc much haiuci
io icmcmlci il cxcciions wcic ol iyc Bioccoli.
Rcmcmlci liom youi olymoihism chaicis ihai
an ol|cci ol iyc Excciion nr lc an insiancc ol any
ubIn ol Excciion.
Bccausc an E:e.or is an ol|cci, whai you nL is an
ol|cci. In ihc lollowing couc, ihc catch aigumcni
is ucclaicu as iyc Excciion, anu ihc aiamcici
iclcicncc vaiiallc is e:.
l': -:l |- -:|.--
. --l- .-----l
1
: :-- --|] ---: .-
!
:-l-- : l---
-
|nterruptedExcept|on
Throwab|e
Except|on
|0Except|on
getHessage(}
pr|nt8tackTrace(}
|.-l - l- !:-l--
:|.:: --.-:] 1-] .||
-l-- :|.:: 1---.|-
.- ---l l-- -]
--l-:
exceptions are objects
Whai you wiiic in a caich llocI uccnus on ihc
cxcciion ihai was ihiown. Ioi cxamlc, il a scivci
is uown you mighi usc ihc caich llocI io iiy anoihci
scivci. Il ihc hlc isn`i ihcic, you mighi asI ihc usci
loi hcl hnuing ii.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
exception handIing
323
|f | !s yeer re4c !hz! rz!rhcs !hc crrcp!|en,
!hcn whesc re4c !hrews | !!
You`ll scnu much moic ol youi ]ava couing iimc LnrJI.r
cxcciions ihan you`ll scnu .en.r anu L.ow.r ihcm youiscll.
Ioi now, |usi Inow ihai whcn youi couc nII a iisIy mcihou-a
mcihou ihai ucclaics an cxcciion-ii`s ihc iisIy mcihou ihai
L.ow ihc cxcciion lacI io ,ou, ihc callci.
In icaliiy, ii mighi lc you who wioic loih classcs. Ii ically
uocsn`i maiici who wiiics ihc couc... whai maiicis is Inowing
which mcihou L.ow ihc cxcciion anu which mcihou nLe ii.
Whcn somclouy wiiics couc ihai coulu ihiow an cxcciion, ihcy
musi JeIn.e ihc cxcciion.
|- |-,| ,.,,
.a,. ,a, a|,-,
|-,| ,,,-. [|
-.-,.| .- a,,a,-
,,,| |a.| , ,-
.a,,-,.
;- |-,| ,a,
,,,- a- , |-.,a,-
,a, ., |._, ,,,
,- -.-,.|.
public void takeRisk() throws BadException {
if (abandonAllHope) {
throw new BadException();
}
}
:--.
l
- .
---
!
:-
l
-
-
-
-:l
.
-
l
--
-
l
l: -
-l- M
c
1
l-|| l- ---| |]
-:|.--` l.l l l---: . B
.!
:-l--
public void crossFingers() {
try {
anObject.takeRisk();
} catch (BadException ex) {
System.out.println(Aaargh!);
ex.printStackTrace();
}
| ]-- :.-'l --:--- --- l- -:-l--, .l |!A1 -l . :l.: l-.:- -:- l- --ll.:1-.:-|` --l- l.l .|| -:-l--: ---l
cIoss wifh o
risky mefhod
f
h
r
o
w
s on excep
fio
n
b
o
c
k
class Cow {
void moo() {
if (serverDown){
explode();
}
}
}
your code
class Bar {
void go() {
moo();
}
int stuff() {
x.beep();
}
}
coIIs risky mefhod
1
2
Risky, exception-throwing code:
Your code that calls the risky method:
1
2
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
324
chapter 11
(-,- a,- |
oa|| qa--(:|-
Wait just a minutel How come this is the FIRS7 time
we've had to try/catch an xception! What about the
exceptions I've aIready gotten Iike NuIIPointerxception
and the exception for DivideyZero. I even got a
NumberFormatxception from the Integer.parseInt()
method. How come we didn't have to catch those!
The compiler cares about all subclasses of Lxception,
unless they are a special type, PuntimeLxception. Any
exception class that extends PuntimeLxception gets a
free pass. PuntimeLxceptions can be thrown anywhere,
with or without throws declarations or try/catch blocks.
The compiler doesn't bother checking whether a method
declares that it throws a PuntimeLxception, or whether the
caller acknowledges that they might get that exception at
runtime.
I'II bite. WHY doesn't the compiIer care about those
runtime exceptions! Aren't they just as IikeIy to bring the
whoIe show to a stop!
Most PuntimeLxceptions come from a problem in
your code logic, rather than a condition that fails at runtime
in ways that you cannot predict or prevent. ou connot
guarantee the file is there. ou connot guarantee the server
is up. 8ut you con make sure your code doesn't index off the
end of an array (that's what the .length attribute is for).
ou wANT PuntimeLxceptions to happen at development
and testing time. ou don't want to code in a try/catch, for
example, and have the overhead that goes with it, to catch
something that shouldn't happen in the first place.
A try/catch is for handling exceptional situations, not flaws
in your code. Use your catch blocks to try to recover from
situations you can't guarantee will succeed. Or at the very
least, print out a message to the user and a stack trace, so
somebody can figure out what happened.
The compiler checks for everything
except RuntimeExceptions.
The compiler guarantees:
--l--!:-l--: .-- N61 :-:- ] l-
:--|-- 1-]'-- ---- .: | :---:- ---`
--:-:- -:-l--:' /-- :.- l---, :.l:,
.- -:|.-- --l--!:-l--:, -l ]-- --'l
.- l-, .- l- :--|-- ---'l :-:
|nterruptedExcept|on
Except|on
|0Except|on Runt|meExcept|on
Nu||Po|nterExcept|on 6|ass6astExcept|on
!:-l--: l.l .-- N61 :-:|.::-: -
--l--!:-l-- .-- :-:- -- ]
l- :--|-- 1-]'-- :.||- :-:-
-:-l--:'
|f you thtow an exception in your code you must declare it using
the thtows keyword in your method declaration.
|f you coll a method that throws an exception (in other words,
a method that Jeclotes it throws an exception), you must
oclnowleJe that you're aware of the exception possibility.
One way to satisfy the compiler is to wrap the call in a try/catch.
( There's a second way we'll look at a little later in this chapter.)
checked and unchecked exceptions
1
2
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
325
8ll P0lk5
A rel|od car l|roW ar excepl|or W|er sorel||r la||s al rurl|re.
Ar excepl|or |s a|Ways ar oojecl ol lype Excepl|or. (w||c|, as you
rereroer lror l|e po|yrorp||sr c|aplers rears l|e oojecl |s lror a
c|ass l|al |as Excepl|or soreW|ere up |ls |r|er|larce lree.)
T|e corp||er does N0T pay allerl|or lo excepl|ors l|al are ol
lype Runt|meExcept|on. A Rurl|reExcepl|or does rol |ave lo oe
dec|ared or Wrapped |r a lry/calc| (a|l|ou| you're lree lo do e|l|er or
ool| ol l|ose l||rs)
A|| Excepl|ors l|e corp||er cares aooul are ca||ed 'c|ec|ed
excepl|ors' W||c| rea||y rears oom||er-c|ec|ed excepl|ors. 0r|y
Rurl|reExcepl|ors are exc|uded lror corp||er c|ec||r. A|| ol|er
excepl|ors rusl oe ac|roW|eded |r your code, accord|r lo l|e
ru|es.
A rel|od l|roWs ar excepl|or W|l| l|e |eyWord throw, lo||oWed oy
a reW excepl|or oojecl:
throw new NoCaffeineException();
Vel|ods l|al m|gnr l|roW a c|ec|ed excepl|or arrource |l W|l|
a throws Exception dec|aral|or.
ll your code ca||s a c|ec|ed-excepl|or-l|roW|r rel|od, |l rusl
reassure l|e corp||er l|al precaul|ors |ave oeer la|er.
ll you're prepared lo |ard|e l|e excepl|or, Wrap l|e ca|| |r a lry/calc|,
ard pul your excepl|or |ard||r/recovery code |r l|e calc| o|oc|.
ll you're rol prepared lo |ard|e l|e excepl|or, you car sl||| ra|e l|e
corp||er |appy oy oll|c|a||y 'duc||r' l|e excepl|or. we'|| la|| aooul
duc||r a ||ll|e |aler |r l||s c|apler.
Which of these do you think
might throw an exception that
the compiIer wouId care about!
We're onIy Iooking for the
things that you can't controI in
your code. We did the rst one.
(8ecause it was the easiest.)
__ connect to a remote server
__ access an array beyond its length
__ display a window on the screen
__ retrieve data from a database
__ see if a text le is where you it is
__ create a new le
__ read a character from the command-line
+,-+ :+ ,-+:.|
7hings you want to do
__________________________________
__________________________________
__________________________________
__________________________________
__________________________________
__________________________________
__________________________________
What might go wrong
l- :---- : ---
ezca||re |(
ll you're lry|r lo |earr sorel||r reW,
ra|e l|al l|e |asr l||r you lry lo |earr
oelore o|r lo s|eep. 3o, orce you pul l||s
ooo| doWr (assur|r you car lear yourse|l
aWay lror |l) dor'l read aryl||r e|se rore
c|a||er|r l|ar l|e oac| ol a C|eer|os
oox. Your ora|r reeds l|re lo process W|al
you've read ard |earred. T|al cou|d la|e
a leW nours. ll you lry lo s|ove sorel||r
reW |r r||l or lop ol your Java, sore ol l|e
Java r||l rol 'sl|c|.'
0l course, l||s doesr'l ru|e oul |earr|r
a p|ys|ca| s||||. wor||r or your |alesl
8a||roor K|c|8ox|r roul|re
prooao|y Wor'l allecl your
Java |earr|r.
For l|e oesl resu|ls, read l||s
ooo| (or al |easl |oo| al
l|e p|clures) r||l oelore
o|r lo s|eep.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
chapter 11
try {
Foo f = x.doRiskyThing();
int b = f.getNum();
} catch (Exception ex) {
System.out.println(failed);
}
System.out.println(We made it!);
exceptions and fIow controI
|-:l l- l-] |-: ---:,
l-- l- :-- -|-- l-
:.l: ---:
File Edit Window Help RiskAll
%java Tester
We made it!
Whcn you call a iisIy mcihou, onc ol iwo ihings can ha-
cn. Thc iisIy mcihou ciihci succccus, anu ihc iiy llocI
comlcics, oi ihc iisIy mcihou ihiows an cxcciion lacI io
youi calling mcihou.
I|ew ren!re| |n !ry/rz!rh ||erks
f the try succeeds
{doRiskyThing{} does not
throw an exception}
1
try {
Foo f = x.doRiskyThing();
int b = f.getNum();
} catch (Exception ex) {
System.out.println(failed);
}
System.out.println(We made it!);
1
- l-] |-: ---:, -l l-
:.|| l- -:]1
-|` l---:
.- -:-l--, :- l- --:l -
l- l-] |-: --:-'l ---
1
- :.l: |-: ---:, l--
l- --l- :--l---: --
File Edit Window Help RiskAll
%java Tester
failed
We made it!
f the try fails
{because doRiskyThing{}
does throw an exception}
1
- --:l - l- l
-] |-: --~
-- ---:, -
: : . 6
-- 1
-
-:.-:- l- --:l - l- l-]
---: -- l- :-::-:: -
l- :.|| l- -
:]1
-|`
2
1
2
3
1- :-- - l-
:.l: |-: ----
---:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
327
Il you iiy io cooI somcihing, you siaii ly iuining on
ihc ovcn.
Il ihc ihing you iiy is a comlcic Iailurc
you hove to turn o[[ the oven.
Il ihc ihing you iiy succccds,
you hove to turn o[[ the oven.
You hove to turn o[[ the oven no motter whot:
Are you sure
you wonf fo fry
fhis7
Mo moffer whof, do MOT Ief
me forgef fo furn off fhe
ovenl Losf fime I forched hoIf
fhe neighborhood.
I|nz||y: fer !hc !h|n]s yee wzn!
!e 4e ne mz!!cr whz!.
A hnally block is where you put
code that must run regardless
of an exception.
try {
turnOvenOn();
x.bake();
turnOvenOff();
} catch (BakingException ex) {
ex.printStackTrace();
turnOvenOff();
}
Wiihoui hnally, you havc io ui ihc
iuinOvcnOll) in ihc iiy anu ihc caich
lccausc you hove to turn o[[ the oven no motter
whot. A hnally llocI lcis you ui all youi
imoiiani clcanu couc in lacc insicau ol
uulicaiing ii liIc ihis:
try {
turnOvenOn();
x.bake();
} catch (BakingException ex) {
ex.printStackTrace();
} nally {
turnOvenOff();
}
f the try block fails {an exception}, fIow
controI immediateIy moves to the catch bIock.
When the catch bIock compIetes, the finaIIy
bIock runs. When the finaIIy bIock compIetes,
the rest of the method continues on.
f the try block succeeds {no exception},
fIow controI skips over the catch bIock and
moves to the finaIIy bIock. When the finaIIy
bIock compIetes, the rest of the method
continues on.
f the try or catch block has a return
statement, hnally will still runl FIow
jumps to the finaIIy, then back to the return.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
chapter 11
Look at the code to the Ieft. What do you think the
output of this program wouId be! What do you think
it wouId be if the third Iine of the program were
changed to: String test = "yes", !
Assume Scaryxception extends xception.
+,-+ :+ ,-+:.|
public class TestExceptions {
public static void main{String args| {
String test = "no",
try {
System.out.println{"start try"|,
doRisky{test|,
System.out.println{"end try"|,
} catch { ScaryException se| {
System.out.println{"scary exception"|,
} nally {
System.out.println{"nally"|,
}
System.out.println{"end of main"|,
}
static void doRisky{String test| throws ScaryException {
System.out.println{"start risky"|,
if {"yes".equals{test|| {
throw new ScaryException{|,
}
System.out.println{"end risky"|,
return,
}
}
Dutput when test = "no"
Dutput when test = "yes"
w h e n t e s t " n o : s t a r t t r y - s t a r t r i s k y - e n d r i s k y - e n d t r y - n a l l y - e n d o f m a i n
w h e n t e s t " y e s : s t a r t t r y - s t a r t r i s k y - s c a r y e x c e p t i o n - n a l l y - e n d o f m a i n
I|ow 0onIro|
fIow controI exercise
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
329
public class Foo {
public void go() {
Laundry laundry = new Laundry();
try {
laundry.doLaundry();
} catch(PantsException pex) {
// recovery code
} catch(LingerieException lex) {
// recovery code
}
}
}
A mcihou can ihiow muliilc cxcciions il ii uain wcll nccus io. Bui
a mcihou`s ucclaiaiion musi ucclaic ihc chccIcu cxcciions ii can
ihiow alihough il iwo oi moic cxcciions havc a common suciclass, ihc
mcihou can ucclaic |usi ihc suciclass.)
P|4 wc mcn!|en !hz! z mc!he4 rzn
!hrew merc !hzn enc crrcp!|en!
Thc comilci will maIc suic ihai you`vc hanulcu ihc chccIcu cxcc-
iions ihiown ly ihc mcihou you`ic calling. SiacI ihc llocIs unuci
ihc , onc alici ihc oihci. Somciimcs ihc oiuci in which you siacI ihc
caich llocIs maiicis, lui wc`ll gci io ihai a liiilc laici.
0z!rh|n] me| !|p|c crrcp!|ens
public class Laundry {
public void doLaundry() throws PantsException, LingerieException {
// code that could throw either exception
}
}
1
: --l- -:|.--: l--, :---l '--,
1
w
6 -:-l--:
-|.---]|` l---: .
|.-l:!:-l--, l |.-: - l-
|.-l:!:-l-- :.l: |-:
-|.---]|` l---: .
|----!:-l--, l |.-: - l-
|----!:-l-- :.l: |-:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
330
chapter 11
Excciions aic ol|ccis, icmcmlci. Thcic`s noihing all ihai
sccial aloui onc, cxcci ihai ii is n L.r Ln nr be .
So liIc all goou ol|ccis, Excciions can lc iclciicu io
olymoihically. A IingciicExcciion obe, loi cxamlc,
coulu lc assigncu io a CloihingExcciion .ee.ere. A
PanisExcciion coulu lc assigncu io an Excciion iclcicncc.
You gci ihc iuca. Thc lcnchi loi cxcciions is ihai a mcihou
uocsn`i havc io cxliciily ucclaic cvciy ossillc cxcciion ii
mighi ihiow, ii can ucclaic a suciclass ol ihc cxcciions.
Samc ihing wiih caich llocIs-you uon`i havc io wiiic a caich
loi cach ossillc cxcciion as long as ihc caich oi caichcs)
you havc can hanulc any cxcciion ihiown.
Irrcp!|ens zrc pe|ymerph|r
You can DECLARE exceptions using
a supertype of the exceptions you
throw.
A|| -:-l--: .-
!:-l-- .: .
:---:|.::
Except|on
|0Except|on
1
public void doLaundry() throws ClothingException {
l-:|.-- . c|-l-!:-l-- |-l: ]-- l---
.-] :-:|.:: - c|-l-!:-l-- 1.l --.-:
-|.---]|` :.- l--- . |.-l:!:-l--,
|----!:-l--, 1---l!:-l--, .-
l--::-l!:-l-- -l--l -|:l|] -:|.-- l--
--.||]
You can CATCH exceptions using a
supertype of the exception thrown.
2
try {
laundry.doLaundry();
} catch(ClothingException cex) {
// recovery code
}
try {
laundry.doLaundry();
} catch(ShirtException sex) {
// recovery code
}
:.- :.l: --|]
1---l!:-l-- .-
l
--::-l!:-l--
:.- :.l: .-]
c|-l-!:-l--
:-:|.::
6|oth|ngExcept|on
PantsExcept|on L|nger|eExcept|on 8h|rtExcept|on
Tee8h|rtExcept|on
0ress8h|rtExcept|on
poIymorphic exceptions
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
331
You ouIJ wiiic youi cxcciion-hanuling couc so ihai
you sccily only ore caich llocI, using ihc suciiyc
Excciion in ihc caich clausc, so ihai you`ll lc allc io
caich nr, cxcciion ihai mighi lc ihiown.
Just because you CAN catch everything
with one big super polymorphic catch,
doesn't always mean you 8HOULD.
try {
laundry.doLaundry();
} catch(Exception ex) {
// recovery code...
}
-:---] --- w+A1 1: :.l: |-: -||
:.l: AN/ .- .|| -:-l--:, :- ]-- ---'l
.-l--.l:.||] --- -.l ---l ----
Ioi cxamlc, il youi couc ucals wiih oi iccovcis
liom) a TccShiiiExcciion uillcicnily ihan ii hanulcs a
IingciicExcciion, wiiic a caich llocI loi cach. Bui il you
iicai all oihci iycs ol CloihingExcciion in ihc samc way,
ihcn auu a CloihingExcciion caich io hanulc ihc icsi.
Write a different catch block for each
exception that you need to handle
uniquely.
try {
laundry.doLaundry();
} catch(TeeShirtException tex) {
// recovery from TeeShirtException
} catch(LingerieException lex) {
// recovery from LingerieException
} catch(ClothingException cex) {
// recovery from all others
}
1
---l!
:-l--: .-
|
----!
:-l--: --- ----l
--:---] :--, :- ]-- :--| -:-
----l :.l: |-::
A|| -l-- c|-l-!:-l--:
.-- :.-l ---
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
332
chapter 11
Thc highci u ihc inhciiiancc iicc, ihc liggci ihc
caich lasIci`. As you movc uown ihc inhciiiancc
iicc, iowaiu moic anu moic sccializcu Excciion
classcs, ihc caich lasIci` is smallci. Ii`s |usi lain olu
olymoihism.
A ShiiiExcciion caich is lig cnough io iaIc
a TccShiiiExcciion oi a DicssShiiiExcciion
anu any luiuic sulclass ol anyihing ihai cxicnus
ShiiiExcciion). A CloihingExcciion is cvcn liggci
i.c. ihcic aic moic ihings ihai can lc iclcicnccu
using a CloihingExcciion iyc). Ii can iaIc an
cxcciion ol iyc CloihingExcciionuuh), anu
any CloihingExcciion sulclasscs: PanisExcciion,
UniloimExcciion, IingciicExcciion, anu
ShiiiExcciion. Thc moihci ol all caich aigumcnis
is iyc Exccption, ii will caich cxcciion,
incluuing iuniimc unchccIcu) cxcciions, so you
iolally won`i usc ii ouisiuc ol icsiing.
Me| !|p|c rz!rh ||erks mes! |c er4crc4
frem smz||cs! !e ||]]cs!
Un|formExcept|on
6|oth|ngExcept|on
PantsExcept|on L|nger|eExcept|on 8h|rtExcept|on
Tee8h|rtExcept|on 0ress8h|rtExcept|on
catch(TeeShirtException tex)
catch(ShirtException sex)
catch(ClothingException cex)
1
---l!
:-l--: .--
:.-l ---, -l -- -l--
-:-l--: -
|| l
1
---l!
:-l--: -
||
---- -l ---, -l .||
-l-- -l!
:-l--
:-:|.::-: .-- :.-l ---
A
|| c
|-l-!
:-l--:
.-- :.-l ---, .|l--
1
---l!
:-l-- .-
-l!
:-l-- -
|| ----
-l l: .-
order of muItipIe catch bIocks
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
exception handIing
333
try {
laundry.doLaundry();
} catch(ClothingException cex) {
// recovery from ClothingException
} catch(LingerieException lex) {
// recovery from LingerieException
} catch(ShirtException sex) {
// recovery from ShirtException
}
Si;e moffers when
you hove muIfipIe cofch
bIocks. The one wifh fhe biggesf
boskef hos fo be on fhe boffom.
Ofherwise, fhe ones wifh
smoIIer boskefs ore useIess.
Yee rzn! pe! ||]]cr |zskc!s
z|evc smz||cr |zskc!s.
Wcll, you lui ii won`i comilc. Caich
llocIs aic noi liIc ovciloaucu mcihous
whcic ihc lcsi maich is icIcu. Wiih caich
llocIs, ihc ]VM simly siaiis ai ihc hisi onc
anu woiIs iis way uown uniil ii hnus a caich
ihai`s lioau cnough in oihci woius, high
cnough on ihc inhciiiancc iicc) io hanulc
ihc cxcciion. Il youi hisi caich llocI is
catch(Exception ex), ihc comilci
Inows ihcic`s no oini in auuing any
oihcis-ihcy`ll ncvci lc icachcu.
S:l|:ags :aa le :a aay a:Je:, le:aase they
:aa't :at:h aae aaathe:'s ex:et:aas.
ou could put ShirtLxception above
LingerieLxception and nobody would mind.
8ecause even though ShirtLxception is a bigger
(broader) type because it can catch other classes
(its own subclasses), ShirtLxception can't catch a
LingerieLxception so there's no problem.
l
-
-
'l
-
l
:'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
334
chapter 11
poIymorphic puzzIe
|ffEx
FooEx
arEx
try {
x.doRisky();
} catch(AlphaEx a) {
// recovery from AlphaEx
} catch(BetaEx b) {
// recovery from BetaEx
} catch(GammaEx c) {
// recovery from GammaEx
} catch(DeltaEx d) {
// recovery from DeltaEx
}
azEx
o|nkEx
Assume the try/catch block here is legally coded. our task is to draw
two different class diagrams that can accurately ren ect the Lxception
classes. |n other words, what class inheritance structures would make the
try/catch blocks in the sample code legalI
our task is to create two different try / catch structures (similar to
the one above left), to accurately represent the class diagram shown on
the left. Assume ALL of these exceptions might be thrown by the method
with the try block.
+,-+ :+ ,-+:.|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
335
Whcn yee 4en! wzn! !e hzn4|c
zn crrcp!|en...
f you don't want to handle an
exception, you can duck it by
declaring it.
Whcn you call a iisIy mcihou, ihc comilci
nccus you io acInowlcugc ii. Mosi ol ihc iimc,
ihai mcans wiaing ihc iisIy call in a iiy/
caich. Bui you havc anoihci alicinaiivc, simly
JuI ii anu lci ihc mcihou ihai callcu ,ou caich
ihc cxcciion.
Ii`s casy-all you havc io uo is JeIn.e ihai
,ou ihiow ihc cxcciions. Evcn ihough,
icchnically, ,ou aicn`i ihc onc uoing ihc
ihiowing, ii uocsn`i maiici. You`ic siill ihc onc
lciiing ihc cxcciion whiz iighi on ly.
Bui il you uucI an cxcciion, ihcn you uon`i
havc a iiy/caich, so whai hacns whcn ihc
iisIy mcihou uoIaunuiy)) Joe ihiow ihc
cxcciion.
Whcn a mcihou ihiows an cxcciion, ihai
mcihou is ocu oll ihc siacI immcuiaicly,
anu ihc cxcciion is ihiown io ihc ncxi
mcihou uown ihc siacI-ihc nIIe.. Bui il ihc
nIIe. is a JuIe., ihcn ihcic`s no caich loi ii so
ihc nIIe. os oll ihc siacI immcuiaicly, anu
ihc cxcciion is ihiown io ihc ncxi mcihou
anu so on... whcic uocs ii cnu. You`ll scc a
liiilc laici.
ju
s
t d
u
c
k
|t
Whof fhe...7
There is MO woy I'm
cofching fhof fhing. I'm geffin'
ouf of fhe woy-- somebody
behind me con hondIe if.
public void foo() throws ReallyBadException {
// call risky method a try/catch
laundry.doLaundry();
}
/
-- --'l !A
|
|
/
l--- l, -l
:-:- ]-- --'l .- . l-]/:.l:
-- l- -:] --l- ]-- :.||,
/
6c
.-- --- l- -:] --l-'
B
-:.-:- ---, ----- :.||: /
6c
.: l- -.| -l l- -:-l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
chapter 11
handIe or decIare
Perk|n] ||y 4cr|zr|n]I en|y
4c|zys !hc |ncv| !z||c
8ooner or later, somebody has to
deal with it. But what if main{}
ducks the exception?
public class Washer {
Laundry laundry = new Laundry();
public void foo() throws ClothingException {
laundry.doLaundry();
}
public static void main (String[] args) throws ClothingException {
Washer a = new Washer();
a.foo();
}
}
B
-
l
-
-l
:
-:
l
- -
:-
l
-
-
|
]
-:|.
-- l
` :-
l
---': --
]
l
-
.
-
|- l
' 1
: :-
-
|-: -:l
--
moin
moin
foo
doLoundry
moin
foo
The JVM
shufs down
We're using the tee-shirt to represent a Clothing
Exception. We know, we know... you would
have preferred the blue jeans.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
337
8o now we've seen both ways to satisfy the compiler
when you call a risky {exception-throwing} method.
Handle or Declare. t's the law.
HANDLE 1
try {
laundry.doLaundry();
} catch(ClothingException cex) {
// recovery code
}
Wrop fhe risky coII in o fry/cofch
1: . -ll-- - . ---- :.l: l- .-|- .|| -:-l--: l.l -|.---]| `
-l l--- 6- -|:- l- :--|-- -||
:l|| :--|.- l.l ]--'-- --l :.l:- .|| - l- -:-l--:
DECLARE {duck it} 2
void foo() throws ClothingException {
laundry.doLaundry();
}
DecIore fhof YOUP mefhod fhrows fhe some excepfions
os fhe risky mefhod you're coIIing.
8uf now fhis meons fhof whoever coIIs fhe foo() mefhod
hos fo foIIow fhe HondIe or DecIore Iow. If foo() ducks
fhe excepfion (by decIoring if), ond moin() coIIs foo(), fhen
moin() hos fo deoI wifh fhe excepfion.
public class Washer {
Laundry laundry = new Laundry();
public void foo() throws ClothingException {
laundry.doLaundry();
}
public static void main (String[] args) {
Washer a = new Washer();
a.foo();
}
} B-:.-:- l- --|` --l- -:: l-
c|-l-!:-l-- l---- ] -|.---]|`,
-.-|` .: l- --. .--|` - . l-]/:.l:,
-- -.-|` .: l- -:|.-- l.l l, l--,
l---: c|-l-!:-l--'
N
-- -
.-|` ---'l :--
|-, .- --
-l .- ------l- -:-l--' -----
A
: .- .: l- :--
|--': :--:----,
l- --|` -
-l- l---: .-
-:-l--
16cB|!''
1- -|.---]|` --l- l---: .
c|-l-!:-l--, -l ] -:|.-- l-
-:-l--, l- --|` --l- -l: l-
-: l- -:-l-- N- l-]/:.l:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
chapter 11
fixing the Sequencer code
public void play() {
try {
Sequencer sequencer = MidiSystem.getSequencer();
System.out.println(Successfully got a sequencer);
} catch(MidiUnavailableException ex) {
System.out.println(Bummer);
}
} // close play
Now ihai you`vc comlcicly loigoiicn, wc siaiicu ihis chaici
wiih a hisi looI ai somc ]avaSounu couc. Wc cicaicu a Sc-
qucncci ol|cci lui ii woulun`i comilc lccausc ihc mcihou
Miui.gciScqucncci) ucclaics a chccIcu cxcciion MiuiUnavail-
allcExcciion). Bui wc can hx ihai now ly wiaing ihc call in a
iiy/caich.
0c!!|n] |zrk !e eer mes|r re4c...
N- --|-- :.||- -l----:--|`,
--- l.l --'- --.- l - . l-]/
:.l: |-:
1
- :.l
: .-.-
-l
-- .: l
- -
l
- '-l
' -
:-l
-- |
-
- :.
':.l
:||
|-N
-l
|
---
!
:-l
--
`, l
-
:-
- -
--|
--l
:--
|-, -:.-:- -|]~
-
--:.||] . M
c
-.|.|-!
:-l
--
-
--'l
l
-l
- . |
|-N
-l
|
---
!
:-l
--
--
--
-- l
': --l
---- l
- .- .
:.l
: |-: ]-- .- l
- :.l
: l
-
l
- -- l
---
-'
You cannot have a catch or hnally
without a try
Irrcp!|en Ke|cs
void go() {
Foo f = new Foo();
f.foof();
catch(FooException ex) { }
}
N61
|
!6A|
'
w
---': l- l-]
You cannot put code between the
try and the catch
try {
x.doStuff();
}
int y = 43;
} catch(Exception ex) { }
N61
|!6A|
' /-- :.-'l -l
:-- -l---- l- l-] .-
l- :.l:
A try MU8T be followed by either a
catch or a hnally
try {
x.doStuff();
} hnally {
// cleanup
}
|
!
6
A
|
-:.-:- ]--
.- . -.||], ---
l-- l---': -- :.l:
B
-l ]-- :.---l .- .
l-] ] l:-|
1
2
3
A try with only a hnally {no catch}
must still declare the exception.
void go() throws FooException {
try {
x.doStuff();
} hnally { }
}
4
A l-] -l--l . :.l:
--:-'l :.l:] l-
.-|- -- -:|.-- |.-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
339
CaJe kit:hea
There is MO woy
I'm Ieffing 8effy win fhe
code-off fhis yeor, so I'm
gonno moke if myseIf from
scrofch.
8uf why don'f
you jusf use
Peody-boke code7
)aa Jaa't have ta Ja it
yaa:se|I, lat it's a |at
a:e Iaa iI yaa Ja.
The :est aI this :hate:
is atiaaa| yaa :aa ase
keaJy-la|e :aJe Ia: a||
the asi: as.
5at iI yaa vaat ta |ea:a
a:e alaat JavaSaaaJ,
ta:a the age.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
chapter 11
Rcmcmlci ncai ihc lcginning ol ihc chaici, wc looIcu ai how MIDI uaia holus
ihc insiiuciions loi wLn shoulu lc laycu anu Low ii shoulu lc laycu) anu wc
also saiu ihai MIDI uaia uocsn`i aciually .ene nr, ourJ Ln ,ou Len.. Ioi sounu
io comc oui ol ihc scaIcis, ihc MIDI uaia has io lc scni ihiough somc Iinu ol
MIDI ucvicc ihai iaIcs ihc MIDI insiiuciions anu icnucis ihcm in sounu, ciihci
ly iiiggciing a haiuwaic insiiumcni oi a viiiual` insiiumcni soliwaic synihc-
sizci). In ihis looI, wc`ic using only soliwaic ucviccs, so hcic`s how ii woiIs in
]avaSounu:
Mzk|n] zr!ez| seen4
You need FOUR things:
8equencer
pIoys hos o
Midi
Event
Midi
Event
Midi
Event
8equence
Track
Midi
Event hoIds
The Sequencer is the thing
that actually causes a song
to be played. Think of it like
a music CD pIayer.
The Sequence is the
song, the musical piece
that the Sequencer will
play. Por this book, think
of the Sequence as a
music CD, but the whoIe
CD pIays just one song.
Por this book, we only
need one Track, so |ust
imagine a a music CD
with only one song. A
single Track. This Track
is where all the song
data (M|D| information)
lives.
1
The thing thut
pIuys the music
2
The music to be
pIuyed,,,u song,
3
The purt of the
Sequence thut
hoIds the uctuuI
informution
4
The uctuuI music
informution:
notes to pIuy
how Iong etc,
A M|D| event is a message
that the Sequencer can
understand. A M|D| event
might say (if it spoke
Lnglish), "At this moment
in time, play middle C, play
it this fast and this hard,
and hold it for this long. "
A M|D| event might
also say something like,
"Change the current
instrument to Plute.
|
-- l: --, l- - l- ----:- .: .
:-|-~
:-- c
l
|.: --|] --- 1
-.:` 1
-
----
.l-- .--l --
l- |.] l- :--
|-: -- l- 1
-.:, .- l- 1
-.: : .-l
- l- ----:-
JavaSound MIDI cIasses
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
341
And you need FVE steps:
--:-'l :--
- .|--.
] ---`
l--'l ----] .--l l- .-----l: l- l-
----:- :--:l--:l-- )-:l :-] l-:- |l-
- '-- .: -.]~.- .-----l: `
A: l- ----:- -- . 1-.: ------, l- 1-.: |-: - l- ----:-, .- l- M|l| .l. |-: - l- 1-.:
|-l :--- M!--l: -l- l- 1-.: 1: .-l
: --:l|] -.]~.- :-- 1- --|] l- ]--'||
.- l- :.-- .--l .-- l- .-----l: l- l-
:-lM-::.-|` --l-, .- l- .-----l: l-
l- M!--l :--:l--:l-- w-'|| |-- .l l-:-
.-----l: -- l- --l .-
l.-l|` l- ----:-- ||- -:- ||A/`
l--'l ---l l- ---l l- - .:.-
Yeer vcry f|rs! seen4 p|zycr zpp
1
2
3
4
Tyc ii in anu iun ii. You`ll hcai ihc sounu ol somconc laying a
singlc noic on a iano! OK, maylc noi somc, lui somc.)
6- l- ----:- l- l- ----:-- ||-
-ll- l- cl - l- cl |.]--`
a sound appIication
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
you are here
exception handIing
343
ShortMessage a = new ShortMessage();
A MiuiEvcni is an insiiuciion loi aii ol a song. A sciics ol MiuiEvcnis is
Iinu ol liIc shcci music, oi a layci iano ioll. Mosi ol ihc MiuiEvcnis wc
caic aloui ucsciilc o thing to do anu ihc moment in time to do it. Thc momcni
in iimc aii maiicis, sincc iiming is cvciyihing in music. This noic lollows
ihis noic anu so on. Anu lccausc MiuiEvcnis aic so uciailcu, you havc io say
ai whai momcni io n. laying ihc noic a NOTE ON cvcni) anu ai whai
momcni io o laying ihc noics NOTE OII cvcni). So you can imaginc
ihai hiing ihc sio laying noic G" NOTE OII mcssagc) beo.e ihc siaii
laying Noic G" NOTE ON) mcssagc woulun`i woiI.
Thc MIDI insiiuciion aciually gocs inio a Mcssagc ol|cci, ihc MiuiEvcni is
a comlinaiion ol ihc Mcssagc lus ihc momcni in iimc whcn ihai mcssagc
shoulu hic`. In oihci woius, ihc Mcssagc mighi say, Siaii laying Miuulc
C" whilc ihc MiuiEvcni woulu say, Tiiggci ihis mcssagc ai lcai 4".
So wc always nccu a Mcssagc anu a MiuiEvcni.
Thc Mcssagc says wLn io uo, anu ihc MiuiEvcni says wLer io uo ii.
Mzk|n] z M|4|Ivcn! |sen] 4z!zI
1 Moke o Messuge
-
l
]
-
:
.
-
-
-
|
-
-
l
-
l
-
|
.
]
-
|
-
:
l
]
Anatomy of a message
I44 meons
MOTE OM
ChunneI
Think of o chonneI Iike o musicion in
o bond. ChonneI I is musicion I (fhe
keyboord pIoyer), chonneI 9 is fhe
drummer, efc.
VeIocity
How fosf ond hord did
you press fhe key7 0 is so soff you
probobIy won'f heor onyfhing, buf I00 is o
good defouIf.
IZ8 meons
MOTE OFF
1
|
o
i
?
+
-
|
7
|i
7
Note to pIuy
A number from 0 fo IZ7, going
from Iow fo high nofes.
1 Messuge type
2
3
4
:
l
.
-
l
|
.
]
:
l
-
|
.
]
|i7
h rst.setMessage(, 1, , 0);
Chunge the instrument
Add o new messoge, 8EFOPE fhe nofe-pIoying messoge,
fhof sefs fhe insfrumenf in chonneI I fo somefhing ofher
fhon fhe defouIf piono. The chonge-insfrumenf messoge
is 'I9Z', ond fhe fhird orgumenf represenfs fhe ocfuoI
insfrumenf (fry o number befween 0 ond IZ7)
3
:
.
-
-
~
-
:
l
-
-
-
-
-
l
-
-
:
:
.
-
:
.
-
-
-
|
|
|
-
-
:
.
-
|
`
l
-
-
:
l
-
-
-
-
-
l
|
o
i
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
chapter 11
This vcision siill lays |usi a singlc noic, lui you gci io usc commanu-linc aigu-
mcnis io changc ihc insiiumcni anu noic. Exciimcni ly assing in iwo ini valucs
liom 0 io 127. Thc hisi ini scis ihc insiiumcni, ihc scconu ini scis ihc noic io lay.
Vcrs|en 2: 0s|n] remmzn4-||nc zr]s !e crpcr|mcn! w| !h seen4s
import javax.sound.midi.*;
public class MiniMusicCmdLine { // this is the hrst one
public static void main(String[] args) {
MiniMusicCmdLine mini = new MiniMusicCmdLine();
if (args.length < 2) {
System.out.println(Don't forget the instrument and note args);
} else {
int instrument = Integer.parseInt(args[0]);
int note = Integer.parseInt(args[1]);
mini.play(instrument, note);
}
} // close main
public void play(int instrument, int note) {
try {
Sequencer player = MidiSystem.getSequencer();
player.open();
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
MidiEvent event = null;
ShortMessage hrst = new ShortMessage();
hrst.setMessage(192, 1, instrument, 0);
MidiEvent changeInstrument = new MidiEvent(hrst, 1);
track.add(changeInstrument);
ShortMessage a = new ShortMessage();
a.setMessage(144, 1, note, 100);
MidiEvent noteOn = new MidiEvent(a, 1);
track.add(noteOn);
ShortMessage b = new ShortMessage();
b.setMessage(128, 1, note, 100);
MidiEvent noteOff = new MidiEvent(b, 16);
track.add(noteOff);
player.setSequence(seq);
player.start();
} catch (Exception ex) {ex.printStackTrace();}
} // close play
} // close class
change the instrument and note
File Edit Window Help Attenuate
%java MiniMusicCmdLine 102 30
%java MiniMusicCmdLine 80 20
%java MiniMusicCmdLine 40 70
-- l -l l-- -l .-: --- o
l- |i7 1-] l-:- -- :l.-l--:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
347
When we're done, we'II hove o working
8eof8ox fhof's oIso o Drum Chof CIienf.
We'II need fo Ieorn obouf 0UIs (incIud-
ing evenf hondIing), I/O, nefworking, ond
fhreods. The nexf fhree chopfers (IZ, I3,
ond I4) wiII gef us fhere.
Where we're headed with the rest
of the CodeKitchens
Andy: groove #2
6hr|s: groove2 rev|sed
N|ge|: dance beat
dance beat
Chapter 15: the goal
-.l --- -.l l-- -.l l--- -.l ---
This CodeIifchen Iefs us buiId o IiffIe
"music video" (bif of o sfrefch fo coII if
fhof...) fhof drows rondom recfongIes fo
fhe beof of fhe MIDI music. We'II Ieorn
how fo consfrucf ond pIoy o Iof of MIDI
evenfs (insfeod of jusf o coupIe, os we do
in fhe currenf chopfer).
Chapter 12: MD events
Mow we'II ocfuoIIy buiId fhe reoI 8eof8ox,
0UI ond oII. 8uf if's Iimifed-os soon os you
chonge o poffern, fhe previous one is Iosf.
There's no Sove ond Pesfore feofure, ond
if doesn'f communicofe wifh fhe nefwork.
(8uf you con sfiII use if fo work on your
drum poffern skiIIs.)
Chapter 13: 8tand-alone
BeatBox
You've mode fhe perfecf poffern, ond
now you con sove if fo o fIe, ond reIood if
when you wonf fo pIoy if ogoin. This gefs
us reody for fhe fnoI version (chopfer Ib),
where insfeod of wrifing fhe poffern fo o
fIe, we send if over o nefwork fo fhe chof
server.
Chapter 14: 8ave and
Restore
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
chapter 11
fs-s cs |s.ss
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
chapter 11
]||(iss ).c
ou know what to do!
Down
2. Currently usable
3. Template's creation
4. Don't show the kids
5. Mostly static AP| class
7. Not about behavior
9. The template
ll. Poll another one off
the line
Across
l. To give value
4. Plew off the top
6. All this and more!
8. Start
l0. The family tree
l3. No ducking
l5. Problem ob|ects
l8. One of 1ava's '49'
More Hints:
A c r o s s 2 0 . A l s o a t y p e o f c o l l e c t i o n
6 . A 1 a v a c h i l d 2 l . Q u a c k
8 . S t a r t a m e t h o d 2 7 . S t a r t s a p r o b l e m
l 3 . | n s t e a d o f d e c l a r e 2 8 . N o t A b s t r a c t
l 2 3
l2 ll l0
8 7
l5
4
24
27
5
6
l8
2l
l4
28
l7
9
l3
l6
l9
22
25
20
23
26
29
20. Class hierarchy
2l. Too hot to handle
24. Common primitive
25. Code recipe
27. Unruly method action
28. No Picasso here
29. Start a chain of events
l2. 1avac saw it coming
l4. Attempt risk
l6. Automatic acquisition
l7. Changing method
l9. Announce a duck
22. Deal with it
23. Create bad news
26. One of my roles
D o w n 9 . O n l y p u b l i c o r d e f a u l t
2 . O r a m o u t h w a s h l 6 . _ _ _ _ _ t h e f a m i l y f o r t u n e
3 . P o r _ _ _ _ _ _ ( n o t e x a m p l e ) l 7 . N o t a ' g e t t e r '
5 . N u m b e r s . . .
puzzIe: crossword
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
you are here
exception handIing
351
class MyEx extends Exception { }
public class ExTestDrive {
public static void main{String args| {
String test = args0,
try {
System.out.print{"t"|,
doRisky{test|,
System.out.print{"o"|,
} catch { MyEx e| {
System.out.print{"a"|,
} nally {
System.out.print{"w"|,
}
System.out.println{"s"|,
}
static void doRisky{String t| throws MyEx {
System.out.print{"h"|,
if {"yes".equals{t|| {
throw new MyEx{|,
}
System.out.print{"r"|,
}
} File Edit Window Help Chill
% java ExTestDrive yes
thaws
% java ExTestDrive no
throws
1. Ialsc, ciihci oi loih.
2. Ialsc, you can ucclaic ihc cxcciion.
S. Tiuc.
4. Ialsc, iuniimc cxcciion can lc caughi.
. Tiuc.
6. Tiuc, loih aic accciallc.
7. Ialsc, ihc ucclaiaiion is sulhcicni.
S. Ialsc, lui il ii uocsn`i ihc ]VM may shui
uown.
9. Tiuc.
10. Ialsc.
11. Tiuc. Ii`s olicn uscu io clcan-u aiiially
comlcicu iasIs.
12. Ialsc.
1S. Ialsc.
14. Ialsc, uucIing is synonomous wiih ucclai-
ing.
1. Ialsc, lioaucsi cxcciions musi lc caughi
ly ihc lasi caich llocIs.
16. Ialsc, il you uon`i havc a caich llocI, you
ucclaic.
17. Ialsc.
fs-s cs |s.ss
]e;ejze o|ajoz
CaJe Kagaets
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
chapter 11
A S S I 0 M M E M T
l 2 3
l2 ll l0
8 7
l5
4
24
27
5
6
l8
2l
l4
28
l7
9
l3
l6
l9
22
25
20
23
26
29
A S S I 0 M M E M T P O P P E D
M C M P
A O S U 8 C L A S S I M V O I E
T P T T V C
H I E P A P C H Y A H A M D L E L
M M H T T A
S C E T E X C E P T I O M S
T E C P M S
A S I E Y W O P D H
M E E E T P E E
T T D U C I C P T
I M T A A L 0 O P I T H M
A E I T A T P
T H P O W S C O M C P E T E O
E A H E M E W
]||(iss nsacis
puzzIe answers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
this is a new chapter 353
12 getting gui
Face it, you need to make GUIs. |f you're building applications that other
people are going to use, you a graphical interface. |f you're building programs for yourself,
you a graphical interface. Lven if you believe that the rest of your natural life will be
spent writing server-side code, where the client user interface is a web page, sooner or later
you'll need to write tools, and you'll want a graphical interface. Sure, command-line apps are
retro, but not in a good way. They're weak, inflexible, and unfriendly. we'll spend two chapters
working on GU|s, and learn key 1ava language features along the way including vent
HandIing and Inner CIasses. |n this chapter, we'll put a button on the screen, and make it do
something when you click it. we'll paint on the screen, we'll display a |peg image, and we'll even
do some animation.
A Very Graphic
8tory
I heord your
ex-wife couId onIy cook
commond-Iine meoIs.
Wowl This Iooks greof.
I guess presenfofion
reoIIy is everyfhing.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
354 chapter 12
/-- --'l . l-: l- l- -.-- --:l|]1- - l- -.-- .: l- l-- .---- l- ----, .- ]-- . l-: l- l- ---- .--
f see one more
command-line app,
you're fired.
A ]Iiamc is ihc ol|cci ihai icicscnis
a winuow on ihc sciccn. Ii`s whcic you
ui all ihc inicilacc ihings liIc luiions,
chccIloxcs, icxi hclus, anu so on. Ii can
havc an honcsi-io-goouncss mcnu lai
wiih mcnu iicms. Anu ii has all ihc liiilc
winuowing icons loi whaicvci lailoim
you`ic on, loi minimizing, maximizing, anu
closing ihc winuow.
Thc ]Iiamc looIs uillcicni uccnuing on
ihc lailoim you`ic on. This is a ]Iiamc on
Mac OS X:
. )|
-.-
- -
l . -
--- .-
.- l-
- '-
-l:' |. -ll--
.- . -.- -ll--`
Making a GU is easy:
your first gui
|! z|| s!zr!s w| !h z w|n4ew
JFrame frame = new JFrame();
Oncc you havc a ]Iiamc, you can ui
ihings wiugcis`) in ii ly auuing ihcm
io ihc ]Iiamc. Thcic aic a ion ol Swing
comoncnis you can auu, looI loi ihcm
in ihc |avax.swing acIagc. Thc mosi
common incluuc ]Buiion, ]RauioBuiion,
]ChccIBox, ]Ialcl, ]Iisi, ]SciollPanc,
]Sliuci, ]TcxiAica, ]TcxiIiclu, anu
]Tallc. Mosi aic ically simlc io usc, lui
somc liIc ]Tallc) can lc a lii moic
comlicaicu.
|e! w|4]c!s |n !hc w|n4ew
Moke o frome (o JFrome)
JButton button = new JButton(click me);
frame.getContentPane().add(button);
1
Moke o widgef (buffon, fexf feId, efc.) 2
Add fhe widgef fo fhe frome 3
frame.setSize(300,300);
frame.setVisible(true);
DispIoy if (give if o si;e ond moke if visibIe) 4
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 355
import javax.swing.*;
public class SimpleGui1 {
public static void main (String[] args) {
JFrame frame = new JFrame();
JButton button = new JButton(click me);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(button);
frame.setSize(300,300);
frame.setVisible(true);
}
}
y[z[ [[z(', z
z]]y @jg @a((n.
The buffon fIIs oII fhe
ovoiIobIe spoce in fhe frome.
Lofer we'II Ieorn fo confroI
where (ond how big) fhe
buffon is on fhe frome.
Yeer f|rs! 00|: z |e!!en en z frzmc
--'l ---l l- ---l l:
:-- .:.-
|]-- :.- .:: l- -ll-- :--:l--:l--
l- l-l ]-- -.-l -- l- -ll--`
- l- -.-- . :--, - -|:
-.||], -.- l :|-'' | ]-- ---l l: :l-, ]-- ---'l :-- .-]l- --- ]-- --- l: :--`
. l- -ll-- l- l- -.--': :--l--l .--
Let's see what happens when we run it:
%ava SimpleGuil
-.- . -.-- .- . -ll--
l: |-- -.-: l- ---.- -l .: :--- .: ]--
:|-:- l- ---- | ]-- |-.- l: --l l -||
-:l :l l--- -- l- ::---- -----`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
356 chapter 12
Thai`s noi cxacily iiuc. Whcn you icss ihc luiion ii shows ihai
icsscu` oi ushcu in` looI which changcs uccnuing on ihc
lailoim looI anu lccl, lui ii always uocs oeL.r io show whcn
ii`s lcing icsscu).
Thc ical qucsiion is, How uo I gci ihc luiion io uo somcihing
sccihc whcn ihc usci clicIs ii."
Be! ne!h|n] hzppcns whcn | r||rk | !...
We need two things:
A method fo be coIIed when fhe user
cIicks (fhe fhing you wonf fo hoppen os
o resuIf of fhe buffon cIick).
1
A woy fo know when fo frigger
fhof mefhod. In ofher words, o woy
fo know when fhe user cIicks fhe
buffonl
2
When the user cIicks, we want
to know.
We're interested in the user-
takes-action-on-a-button event.
(-,- a,- |
oa|| qa--(:|-
WiII a button Iook Iike a
Windows button when you run on
Windows!
|f you want it to. ou can
choose from a few "look and
feelsclasses in the core library
that control what the interface looks
like. |n most cases you can choose
between at least two different looks:
the standard 1ava look and feel, also
known as Mernl and the native look
and feel for your platform. The Mac
OS X screens in this book use either
the OS X Aqun look and feel, or the
Mernl look and feel.
Can I make a program Iook
Iike Aqua aII the time! ven when
it's running under Windows!
Nope. Not all look and feels
are available on every platform. |f
you want to be safe, you can either
explicitly set the look and feel to
Metal, so that you know exactly what
you get regardless of where the app
is running, or don't specify a look
and feel and accept the defaults.
I heard Swing was dog-sIow
and that nobody uses it.
This was true in the past,
but isn't a given anymore. On weak
machines, you might feel the pain of
Swing. 8ut on the newer desktops,
and with 1ava version l.3 and be-
yond, you might not even notice the
difference between a Swing GU| and
a native GU|. Swing is used heavily
today, in all sorts of applications.
user interface events
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 357
Imaginc you wani ihc icxi on ihc luiion io
changc liom I.I e io I`.e beer I.IeJ whcn
ihc usci icsscs ihc luiion. Iiisi wc can wiiic a
mcihou ihai changcs ihc icxi ol ihc luiion a
quicI looI ihiough ihc API will show you ihc
mcihou):
0c!!|n] z escr cvcn!
public void changeIt() {
button.setText(I've been clicked!);
}
Bui row whai. How will wc Irow whcn ihis
mcihou shoulu iun. How wiII we hnow when the
button is cIiched
In ]ava, ihc ioccss ol gciiing anu hanuling a
usci cvcni is callcu e.er-LnrJI.r. Thcic aic
many uillcicni cvcni iycs in ]ava, alihough
mosi involvc GUI usci aciions. Il ihc usci clicIs
a luiion, ihai`s an cvcni. An cvcni ihai says
Thc usci wanis ihc aciion ol ihis luiion io
hacn." Il ii`s a Slow Tcmo" luiion, ihc usci
wanis ihc slow-icmo aciion io occui. Il ii`s a
Scnu luiion on a chai clicni, ihc usci wanis ihc
scnu-my-mcssagc aciion io hacn. So ihc mosi
siiaighiloiwaiu cvcni is whcn ihc usci clicIcu
ihc luiion, inuicaiing ihcy wani an aciion io
occui.
Wiih luiions, you usually uon`i caic aloui any
inicimcuiaic cvcnis liIc luiion-is-lcing-icsscu
anu luiion-is-lcing-iclcascu. Whai you wani io
say io ihc luiion is, I uon`i caic how ihc usci
lays wiih ihc luiion, how long ihcy holu ihc
mousc ovci ii, how many iimcs ihcy changc ihcii
minu anu ioll oll lcloic lciiing go, cic. ]ust teII
me when the user meons business: In oihci woius,
uon`i call mc unlcss ihc usci clicIs in a way ihai
inuicaics hc wanis ihc uain luiion io uo whai ii
says ii`ll uo!"
First, the button needs to know
that we care.
your code
b
u
f
f
o
n o
b
j
e
c
f
+-] -ll--, | :.-- .--l
-.l .--: l- ]--
1
2 1- -:-- :|:- --'
8econd, the button needs a way
to call us back when a button-
clicked event occurs.
l) How could you tell a button ob|ect that you
care about its eventsI That you're a concerned
listenerI
2) How will the button call you backI Assume
that there's no way for you to tell the button the
name of your unique method (change|t()). So
what else can we use to reassure the button that
we have a specific method it can call when the
event happensI |hint: think Pet|
WWkm
w&W
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
358 chapter 12
event Iisteners
A Iistener interfuce is fhe bridge befween fhe
Iistener (you) ond event source (fhe buffon).
<<interfece>>
K
eyListener
|eyPressed(KeyEverl ev) |eyRe|eased(KeyEverl ev)
|eyTyped(KeyEverl ev)
<<interfece>>
/tem
Listener
|ler3laleC|ared(llerEverl ev)
<
<
in
te
r
fe
c
e
>
>
A
c
tio
n
L
is
te
n
e
r
a
c
l|o
r
P
e
rlo
rr
e
d
(A
c
l|o
r
E
v
e
r
l e
v
)
Thc Swing GUI comoncnis aic cvcni souiccs. In ]ava icims,
an cvcni souicc is an ol|cci ihai can iuin usci aciions clicI
a mousc, iyc a Icy, closc a winuow) inio cvcnis. Anu liIc
viiiually cvciyihing clsc in ]ava, an cvcni is icicscnicu as an
ol|cci. An ol|cci ol somc cvcni class. Il you scan ihiough ihc
|ava.awi.cvcni acIagc in ihc API, you`ll scc a lunch ol cvcni
classcs casy io soi-ihcy all havc Event in ihc namc). You`ll
h nu MouscEvcni, KcyEvcni, WinuowEvcni, AciionEvcni, anu
scvcial oihcis.
An cvcni source liIc a luiion) cicaics an event object whcn ihc
usci uocs somcihing ihai maiicis liIc I.I ihc luiion). Mosi
ol ihc couc you wiiic anu all ihc couc in ihis looI) will .ee..e
cvcnis iaihci ihan .ene cvcnis. In oihci woius, you`ll scnu
mosi ol youi iimc as an cvcni I.ere. iaihci ihan an cvcni ou.e.
Evciy cvcni iyc has a maiching lisicnci inicilacc. Il you wani
MouscEvcnis, imlcmcni ihc MouscIisicnci inicilacc. Wani
WinuowEvcnis. Imlcmcni WinuowIisicnci. You gci ihc iuca.
Anu icmcmlci youi inicilacc iulcs-io imlcmcni an inicilacc
you JeIn.e ihai you imlcmcni ii class Dog imlcmcnis Pci),
which mcans you musi w..e .Ieern.or eLoJ loi cvciy
mcihou in ihc inicilacc.
Somc inicilaccs havc moic ihan onc mcihou lccausc ihc
cvcni iiscll comcs in uillcicni u avois. Il you imlcmcni
MouscIisicnci, loi cxamlc, you can gci cvcnis loi
mouscPicsscu, mouscRclcascu, mouscMovcu, cic. Each ol
ihosc mousc cvcnis has a scaiaic mcihou in ihc inicilacc,
cvcn ihough ihcy all iaIc a MouscEvcni. Il you imlcmcni
MouscIisicnci, ihc mouscPicsscu) mcihou is callcu whcn ihc
usci you gucsscu ii) icsscs ihc mousc. Anu whcn ihc usci lcis
go, ihc mouscRclcascu) mcihou is callcu. So loi mousc cvcnis,
ihcic`s only onc cvcni obe, MouscEvcni, lui scvcial uillcicni
cvcni eLoJ, icicscniing ihc uillcicni ,e ol mousc cvcnis.
If you care about the button's events,
implement an interface that says,
"I'm listening for your events."
y[n ya j]n( z
]j,(n jn(|ze, ya gjv
([ a((n z wzy ( ez]]
ya ze[. [[ jn(|ze j,
w[ ([ ez]]-ze[ ([]
j, ]e]z].
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 359
"8uffon, pIeose odd me fo
your Iisf of Iisfeners ond coII
my ocfionPerformed() mefhod
when fhe user cIicks you."
How the listener and source
communicate:
The I:steae:
The lveat Saa::e
|f your class wants to know about
a button's ActionLvents, you
implement the ActionListener
interface. The button needs to
know you're interested, so you
register with the button by calling its
addActionListener(this) and passing an
ActionListener reference to it (in this case,
you are the ActionListener so you pass
th|s).The button needs a way to call you
back when the event happens, so it calls
the method in the listener interface. As an
ActionListener, you must implement the
interface's sole method, actionPerformed().
The compiler guarantees it.
A button is a source of ActionLvents,
so it has to know which ob|ects are
interested listeners. The button has an
addActionListener() method to give
interested ob|ects (listeners) a way to
tell the button they're interested.
when the button's
addActionListener() runs (because
a potential listener invoked it), the
button takes the parameter (a
reference to the listener ob|ect) and
stores it in a list. when the user clicks
the button, the button 'res' the event
by calling the actionPerformed()
method on each listener in the list.
"OI, you're on AcfionLisfener,
so I know how fo coII you bock
when fhere's on evenf -- I'II coII
fhe ocfionPerformed() mefhod
fhof I know you hove."
o
c
fion
P
erformed(fh
e
E
v
e
n
f
)
b
u
f
f
o
n
.
o
d
d
A
cfionLisfener
(
f
h
i
s
)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
360 chapter 12
import javax.swing.*;
import java.awt.event.*;
public class SimpleGui1B implements ActionListener {
JButton button;
public static void main (String[] args) {
SimpleGui1B gui = new SimpleGui1B();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
button = new JButton(click me);
button.addActionListener(this);
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
button.setText(I've been clicked!);
}
}
|-
|--
--l l- -l--
.:- 1
: :.]:,
.- -:l.-:- -
-
|-6
-|B
|
~
A
A
:l--|
:l----'
|1
- -ll-- -
|| - ---l: --|] l-
A
:l--|
:l---- -
|--
--l--:`
--:l-- ]--- -l---:l -
l l- -ll-- 1
: :.]:
l- l- -ll--, A
-
- l- ]--- |:l -
|:l----:'
1
- .---
--l ]-- .:: M
c
1
- .- --:l
---
.
:|.:: l.l -
|--
--l: A
:l--|
:l----''
. --- ---l :l.l----l -- l- .:.- l.l
A:l--|:l---- .- A:l--!--l .-- -
|-|----l l- A:l--|:l---- -l--.:-':
.:l--|------|` --l- 1: : l-
.:l-.| ---l~.-|- --l-'
1- -ll-- :.||: l: --l- l- |-l ]-- --- .- ---l
.--- |l :--: ]-- .- A:l--!--l --:l .: l-
.-----l, -l -- --'l --- l r---- l- ---l .--- : ---- -- -- -:
2
3
1
ImpIemenf fhe AcfionLisfener inferfoce
1
Pegisfer wifh fhe buffon (feII if you
wonf fo Iisfen for evenfs)
2
Defne fhe evenf-hondIing mefhod (impIemenf
fhe ocfionPerformed() mefhod from fhe
AcfionLisfener inferrfoce)
3
Getting a button's ActionEvent
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 361
As on evenf source, my job is fo
uccept regisfrofions (from Iisfeners),
get evenfs from fhe user. ond
cuII fhe Iisfener's evenf-hondIing
mefhod (when fhe user cIicks me)
Ioi mosi ol youi sicllai ]ava caicci, ,ou will noi lc ihc ou.e
ol cvcnis.
No maiici how much you lancy youiscll ihc ccnici ol youi social
univcisc.)
Gci uscu io ii. Your job is to be o good Iistener.
Which, il you uo ii sinccicly, nr imiovc youi social lilc.)
I|s!cncrs, 8eerrcs, zn4 Ivcn!s
As o Iisfener, my job is fo
impIement fhe inferfoce,
register wifh fhe buffon, ond
provide fhe evenf-hondIing.
Listener GET8 the
event
8ource 8END8
the event
Event ob]ect
HOLD8 DATA
about the event
E
v
e
n
f o
b
j
e
c
f
Hey, whof obouf me7 I'm o pIoyer foo, you
knowl As on evenf objecf, I'm fhe urgument
fo fhe evenf coII-bock mefhod (from fhe
inferfoce) ond my job is fo curry dutu obouf
fhe evenf bock fo fhe Iisfener.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
362 chapter 12
(-,- a,- |
oa|| qa--(:|-
Why can't I be a source of events!
ou CAN. we |ust said that most of the time
you'll be the receiver and not the originator of the
event (at least in the eotly days of your brilliant 1ava
career). Most of the events you might care about
are 'fired' by classes in the 1ava AP|, and all you have
to do is be a listener for them. ou might, however,
design a program where you need a custom event, say,
StockMarketLvent thrown when your stock market
watcher app finds something it deems important. |n
that case, you'd make the Stockwatcher ob|ect be an
event source, and you'd do the same things a button
(or any other source) doesmake a listener interface
for your custom event, provide a registration method
(addStockListener()), and when somebody calls it, add
the caller (a listener) to the list of listeners. Then, when
a stock event happens, instantiate a StockLvent ob|ect
(another class you'll write) and send it to the listeners
in your list by calling their stockChanged(StockLvent
ev) method. And don't forget that for every event tye
there must be a motch|n l|stenet |ntetloce (so you'll
create a StockListener interface with a stockChanged()
method).
I don't see the importance of the event object
that's passed to the event caII-back methods. If
somebody caIIs my mousePressed method, what
other info wouId I need!
A lot of the time, for most designs, you don't
need the event ob|ect. |t's nothing more than a little
data carrier, to send along more info about the event.
8ut sometimes you might need to query the event for
specific details about the event. Por example, if your
mousePressed() method is called, you know the mouse
was pressed. 8ut what if you want to know exactly
where the mouse was pressedI |n other words, what if
you want to know the X and screen coordinates for
where the mouse was pressedI
Or sometimes you might want to register the some
listener with mult|le ob|ects. An onscreen calculator,
for example, has l0 numeric keys and since they all do
the same thing, you might not want to make a separate
listener for every single key. |nstead, you might
register a single listener with each of the l0 keys, and
when you get an event (because your event call-back
method is called) you can call a method on the event
ob|ect to find out who the real event source was. |n
other words, wh|ch ley sent th|s event.
+,-+ :+ ,-+:.|
windowClosing()
actionPerformed()
itemStateChanged()
mousePressed()
keyTyped()
mouseExited()
focusGained()
check box
text feld
scrolling list
button
dialog box
radio button
menu item
Widgets Event methods
Lach of these widgets (user interface ob|ects) are the
source of one or more events. Match the widgets with
the events they might cause. Some widgets might be a
source of more than one event, and some events can be
generated by more than one widget.
qw ] ya [0y j|
zn je( j, zn vn(
,ae/
Look in the AP.
0[. j[ | w[z(/
A method that starts with
add', ends with Listener',
and takes a listener inter-
face argument. f you see:
addKeyL|stener(KeyL|stener k}
you know that a class
with this method is a
source of KeyEvents.
There's a naming pattern.
event handIing
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
getting gui
you are here 363
Now ihai wc Inow a liiilc aloui how cvcnis woiI wc`ll lcain
moic laici), lci`s gci lacI io uiiing siull on ihc sciccn.
Wc`ll scnu a lcw minuics laying wiih somc lun ways io gci
giahic, lcloic iciuining io cvcni hanuling.
0c!!|n] |zrk !e ]rzph|rs...
Three ways to put things on your GU:
Put widgets on u frume
Add buffons, menus, rodio buffons, efc.
frame.getContentPane().add(myButton);
The jovox.swing pockoge hos more fhon o do;en
widgef fypes.
1
Put u JPES on u widget
You con puf your own imoges on o widgef.
graphics.drawImage(myPic,10,10,this);
3
Druw ZD gruphics on u widget
Use o grophics objecf fo poinf shopes.
graphics.llOval(70,70,100,100);
You con poinf o Iof more fhon boxes ond circIes,
fhe JovoZD API is fuII of fun, sophisficofed
grophics mefhods.
2
Number of Head
First Java books
mistakenly
bought by coffee
house baristas.
.
-l
, .
-
-:, :-
-|.
l
-
-:, -l
:
:.-l:,
-:--::
-.::,
-l:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
364 chapter 12
Il you wani io ui youi own giahics on ihc sciccn, youi lcsi
lci is io maIc youi own ainiallc wiugci. You lo ihai wiugci
on ihc liamc, |usi liIc a luiion oi any oihci wiugci, lui whcn ii
shows u ii will havc youi imagcs on ii. You can cvcn maIc ihosc
imagcs movc, in an animaiion, oi maIc ihc colois on ihc sciccn
changc cvciy iimc you clicI a luiion.
Ii`s a iccc ol caIc.
Make a subclass of JPanel and override one
method, paintComponent{}.
All ol youi giahics couc gocs insiuc ihc ainiComoncni)
mcihou. ThinI ol ihc ainiComoncni) mcihou as ihc mcihou
callcu ly ihc sysicm io say, Hcy wiugci, iimc io aini youiscll."
Il you wani io uiaw a ciiclc, ihc ainiComoncni) mcihou will
havc couc loi uiawing a ciiclc. Whcn ihc liamc holuing youi
uiawing ancl is uislaycu, ainiComoncni) is callcu anu youi
ciiclc acais. Il ihc usci iconihcs/minimizcs ihc winuow, ihc
]VM Inows ihc liamc nccus icaii" whcn ii gcis uc-iconihcu,
so ii calls ainiComoncni) again. Anyiimc ihc ]VM ihinIs ihc
uislay nccus iclicshing, youi ainiComoncni) mcihou will lc
callcu.
Onc moic ihing, you never coII this method yourseI[: Thc aigumcni
io ihis mcihou a Giahics ol|cci) is ihc aciual uiawing canvas
ihai gcis slacu onio ihc uislay. You can`i gci ihis ly
youiscll, ii musi lc hanucu io you ly ihc sysicm. You`ll scc
laici, howcvci, ihai you asI ihc sysicm io iclicsh ihc uislay
icaini)), which uliimaicly lcaus io ainiComoncni) lcing
callcu.
Mzkc yeer ewn 4rzw|n] w|4]c!
making a drawing paneI
import java.awt.*;
import javax.swing.*;
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.orange);
g.llRect(20,50,100,100);
}
}
]
-- ---
-l
-
l
-:-
M
.- . :-:|.:: - )|.--|, . --l
l.l ]-- :.- . l- . -.-- -:l |-
.-]l- -|:- !:-l l: --- : ]---
--- :-:l---- --l
1: : l- B |---l.-l 6-.:: --l-
/-- -|| N!/! :.|| l: ]---:-| 1-
:]:l-- :.||: l .- :.]:, +---': . -:-
--: -.-- :--.:-, - l]- 6-.::,
l.l ]-- -.] .-l -- ---'
|-.-- l.l '' : . .-l- -.:-- /--'--
l-||- l -.l :-|-- l- .-l -l .- l--
-.l :.- l- .-l |-l :----.l-: --
---- l --: .- -- l :`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 365
Ici`s looI ai a lcw moic ihings you can uo in ainiComoncni).
Thc mosi lun, ihough, is whcn you siaii cxciimcniing youiscll.
Tiy laying wiih ihc numlcis, anu chccI ihc API loi class
Giahics laici wc`ll scc ihai ihcic`s cvcn you can uo lcsiucs
whai`s in ihc Giahics class).
Ien !h|n]s !e 4e |n pz|n!0empencn!|I
public void paintComponent(Graphics g) {
Image image = new ImageIcon(catzilla.jpg).getImage();
g.drawImage(image,3,4,this);
}
public void paintComponent(Graphics g) {
g.llRect(0,0,this.getWidth(), this.getHeight());
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color randomColor = new Color(red, green, blue);
g.setColor(randomColor);
g.llOval(70,70,100,100);
}
|| l- --l-- .--| -
l |.:
|l-
-
.-|l :-|--`
1- -:l l-- .-: --- l- |,]` --- |-l
:-----, --|.l- l- l- .--|, -- ---- -.--
:l.-l:, :- o, o --.-: :l.-l o -|: --- l-
|-l -- .- o -|: --- l- l- --' 1-
-l-- l-- .-: :.], M.- l- -l - l:
--:l.-|- .: -- .: l- .--| |l:-l|``, .-
-.- l- -l .: l.|| .: l- .--| |l:-l`'
]---
|- -.-
- --: ---
1- ,] :----.l-: -- ---- l- :l---': l-
|-l :----- :--| - 1: :.]: ? -|: ---
l- |-l -- - l- .--| .- + -|: --- l-
l- -- - l- .--|' 1-:- -----: .-- .|-.]:
--|.l- l- l- --l |- l: :.:- ]--- )|.--|
:-:|.::`, --l l- --l-- -.--
:l.-l 7o -|: --- l- |-l, 7o ---
l- l-, -.- l |oo -|: --, .-
|oo -|: l.||
/-- :.- -.- . :-|-- ] .::- - ? -l:
l- ----:--l l- 6B .|--:
Display a JPEG
Paint a randomly-colored circle
on a black background
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
366 chapter 12
Thc aigumcni io ainiComoncni) is ucclaicu as iyc
Giahics |ava.awi.Giahics).
Bch|n4 cvcry ]ee4 0rzph|rs rcfcrcnrc
|s z 0rzph|rs2P e|jcr!.
drawing gradients with Graphics2D
public void paintComponent(Graphics g) { } Methods you can call on a
Graphics reference:
drawmage()
drawLine()
drawPolygon
drawRect()
drawOval()
fllRect()
fllRoundRect()
setColor()
So ihc aiamcici g` IS-A Giahics ol|cci. Which mcans ii
ouIJ lc a ubIn ol Giahics lccausc ol olymoihism).
Anu in laci, ii ..
The object re[erenced by the g` porometer is octuoIIy on
instonce o[ the Graphics2D cIoss.
Why uo you caic. Bccausc ihcic aic ihings you can uo wiih
a Giahics2D iclcicncc ihai you can`i uo wiih a Giahics
iclcicncc. A Giahics2D ol|cci can uo moic ihan a Giahics
ol|cci, anu ii ically is a Giahics2D ol|cci luiIing lchinu ihc
Giahics iclcicncc.
Rcmcmlci youi olymoihism. Thc comilci ucciucs which
mcihous you can call lascu on ihc iclcicncc iyc, noi ihc
ol|cci iyc. Il you havc a Dog ol|cci iclcicnccu ly an Animal
iclcicncc vaiiallc:
Animal a = new Dog();
You can NOT say:
a.bark();
Evcn ihough you Inow ii`s ically a Dog lacI ihcic. Thc
comilci looIs ai a`, sccs ihai ii`s ol iyc Animal, anu hnus
ihai ihcic`s no icmoic coniiol luiion loi laiI) in ihc Animal
class. Bui you can siill gci ihc ol|cci lacI io ihc Dog ii ically .
ly saying:
Dog d = (Dog) a;
d.bark();
So ihc loiiom linc wiih ihc Giahics ol|cci is ihis:
II you nccd to usc a mcthod Irom thc Graphics2D class, you
can't use thc thc paintComponcnt paramctcr ('g') straight
Irom thc mcthod. But you can cost it with a ncw Graphics2D
variablc.
Graphics2D g2d = (Graphics2D) g;
Methods you can call on
a Graphics2D reference:
fll3DRect()
draw3DRect()
rotate()
scale()
shear()
transform()
setRenderingHints()
|l-:- .-- --l :--|-l- --l- |:l:,
:-: l- A|| -- ----`
To cast the Graphics2D ob]ect to
a Graphics2D reference:
Graphics2D g2d = (Graphics2D) g;
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 367
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
GradientPaint gradient = new GradientPaint(70,70,Color.blue, 150,150, Color.orange);
g2d.setPaint(gradient);
g2d. llOval(70,70,100,100);
}
Bcrzesc ||fcs !ee sher! !e pz|n! !hc
r|rr|c z se||4 re|er whcn !hcrcs z
]rz4|cn! ||cn4 wz| !|n] fer yee.
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color startColor = new Color(red, green, blue);
red = (int) (Math.random() * 255);
green = (int) (Math.random() * 255);
blue = (int) (Math.random() * 255);
Color endColor = new Color(red, green, blue);
GradientPaint gradient = new GradientPaint(70,70,startColor, 150,150, endColor);
g2d.setPaint(gradient);
g2d. llOval(70,70,100,100);
}
l': --.||] . 6-.::il
--:l
-.:---.- .: . ---- 6-.::
--:l
:.:l l :- -- :.- :.|| :---l- l.l
6-.::il .: -l 6-.:: --:-'l
l: :-l: l- -l-.| .-l --: l- . -.--l -:l-. - . :-| :-|--
:l
.
-
l
-
-
-
l
:l
.
-
l
-
:
-
|-
-
-
-
-
-
l
-
-
:
-
|-
-
l- ||6.||` --l- --.||] --.-: ||
l- -.| -l -.l--- : |-.- -- ]---
.-l--: |- l- -.--l`'
l: : -:l |- l- --- .--,
-:-l l -.-: -.--- :-|--: --
l- :l.-l .- :l- :-|--: - l-
-.--l 1
-] l'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
368 chapter 12
events and graphics
To ra|e a 0ul, slarl W|l| a W|rdoW, usua||y a JFrare
JFrame frame = new JFrame();
You car add W|dels (oullors, lexl l|e|ds, elc.) lo l|e
JFrare us|r:
frame.getContentPane().add(button);
ur|||e rosl ol|er corporerls, l|e JFrare doesr'l |el
you add lo |l d|recl|y, so you rusl add lo l|e JFrare's
corlerl pare.
To ra|e l|e W|rdoW (JFrare) d|sp|ay, you rusl |ve |l
a s|ze ard le|| |l oe v|s|o|e:
frame.setSize(300,300);
frame.setVisible(true);
To |roW W|er l|e user c||c|s a oullor (or la|es sore
ol|er acl|or or l|e user |rlerlace) you reed lo ||sler lor
a 0ul everl.
To ||sler lor ar everl, you rusl re|sler your |rleresl
W|l| ar everl source. Ar everl source |s l|e l||r (oul-
lor, c|ec|oox, elc.) l|al 'l|res' ar everl oased or user
|rleracl|or.
T|e ||slerer |rlerlace |ves l|e everl source a Way
lo ca|| you oac|, oecause l|e |rlerlace del|res l|e
rel|od(s) l|e everl source W||| ca|| W|er ar everl
|appers.
To re|sler lor everls W|l| a source, ca|| l|e source's
re|slral|or rel|od. Re|slral|or rel|ods a|Ways la|e
l|e lorr ol: edd<Event7ye>Listener. To re|sler lor a
oullor's Acl|orEverls, lor exarp|e, ca||:
button.addActionListener(this);
lrp|ererl l|e ||slerer |rlerlace oy |rp|ererl|r a|| ol
l|e |rlerlace's everl-|ard||r rel|ods. Pul your everl-
|ard||r code |r l|e ||slerer ca||-oac| rel|od. For
Acl|orEverls, l|e rel|od |s:
public void actionPerformed(ActionEvent
event) {
button.setText(you clicked!);
}
T|e everl oojecl passed |rlo l|e everl-|ard|er rel|od
carr|es |rlorral|or aooul l|e everl, |rc|ud|r l|e source
ol l|e everl.
8ll P0lk5
6kkPkl65
You car draW 20 rap||cs d|recl|y or lo a W|del.
You car draW a .|l or .jpe d|recl|y or lo a W|del.
To draW your oWr rap||cs (|rc|ud|r a .|l or .jpe),
ra|e a suoc|ass ol JPare| ard overr|de l|e pa|rlCor-
porerl() rel|od.
T|e pa|rlCorporerl() rel|od |s ca||ed oy l|e 0ul
sysler. Y0u NEvER CALL lT Y0uR3ELF. T|e aru-
rerl lo pa|rlCorporerl() |s a 0rap||cs oojecl l|al
|ves you a surlace lo draW or, W||c| W||| erd up or
l|e screer. You carrol corslrucl l|al oojecl yourse|l.
Typ|ca| rel|ods lo ca|| or a 0rap||cs oojecl (l|e pa|rl-
Corporerl pararerler) are:
graphics.setColor(Color.blue);
g.llRect(20,50,100,120);
To draW a .jp, corslrucl ar lrae us|r:
Image image = new ImageIcon(catzilla.
jpg).getImage();
ard draW l|e |ra|re us|r:
g.drawImage(image,3,4,this);
T|e oojecl relererced oy l|e 0rap||cs parareler
lo pa|rlCorporerl() |s aclua||y ar |rslarce ol l|e
0rap||cs20 c|ass. T|e 0rap||cs 20 c|ass |as a var|ely
ol rel|ods |rc|ud|r:
fll3DRect(), draw3DRect(), rotate(), scale(), shear(),
transform()
To |rvo|e l|e 0rap||cs20 rel|ods, you rusl casl l|e
parareler lror a 0rap||cs oojecl lo a 0rap||cs20
oojecl:
Graphics2D g2d = (Graphics2D) g;
k5
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 369
Ici`s hooI u an cvcni io a changc in oui uiawing ancl. Wc`ll maIc ihc ciiclc
changc colois cach iimc you clicI ihc luiion. Hcic`s how ihc iogiam uows:
Wc rzn ]c! zn cvcn!.
Wc rzn pz|n! ]rzph|rs.
Be! rzn wc pz|n! ]rzph|rs whcn wc ]c! zn cvcn!!
-
|~
:
.
-
-
l
l
-
-
-
||
-
-
-
-
---l
:--l
--:l
:--l--
Uh-oh.
Is ihai cvcn ossillc. How uo
you gci cvcnis whcn you
havc only aciionPciloimcu)
mcihou.
n4 wc ncc4 !e ]c!
IW0 cvcn!s
1: -ll-- :.--: l- l-l
-- l- --:l- :-
1: -ll-- :.--: l- :-|--
- l- :-:|-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
getting gui
you are here 373
Hew 4e yee ]c! zr!|en cvcn!s fer ! we 4|ffcrcn! |e!!ens,
whcn czrh |e!!en ncc4s !e 4e semc!h|n] 4|ffcrcn!!
1 option one
mplement two actionPerformed{} methods
Flaw: You can'tl ou can't implement the same method twice in a 1ava class. |t won't compile.
And even if you coulJ, how would the event source know wh|ch of the two methods to callI
class MyGui implements ActionListener {
// lots of code here and then:
public void actionPerformed(ActionEvent event) {
frame.repaint();
}
public void actionPerformed(ActionEvent event) {
label.setText(That hurt!);
}
}
2
option two
Register the same listener with both buttons.
Flaw: this does work, but in most cases it's not very OO. One event handler
doing many different things means that you have a single method doing many different things.
|f you need to change how one source is handled, you have to mess with evetyooJys event
handler. Sometimes it |s a good solution, but usually it hurts maintainability and extensibility.
-:l-- l- :.-- |:l----
-l -l -ll--:
class MyGui implements ActionListener {
// declare a bunch of instance variables here
public void go() {
// build gui
colorButton = new JButton();
labelButton = new JButton();
colorButton.addActionListener(this);
labelButton.addActionListener(this);
// more gui code here ...
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == colorButton) {
frame.repaint();
} else {
label.setText(That hurt!);
}
}
}
6---] l- ---l --:l
l- - --l -: -ll--
.:l-.||] -- l, .- -:-
l.l l- -:- -.l l- -
B-l l: : --::|-'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
374 chapter 12
3
option three
Create two separate ActionListener classes
Flaw: these classes won't have access to the variables they need
to act on, frame' and label'. ou could x it, but you'd have to give each of the
listener classes a reference to the main GU| class, so that inside the actionPerformed()
methods the listener could use the GU| class reference to access the variables of the GU|
class. 8ut that's breaking encapsulation, so we'd probably need to make getter methods
for the gui widgets (getPrame(), getLabel(), etc.). And you'd probably need to add a
constructor to the listener class so that you can pass the GU| reference to the listener at
the time the listener is instantiated. And, well, it gets messier and more complicated.
7here hns ger re be n berrer wnyl
class MyGui {
JFrame frame;
JLabel label;
void gui() {
// code to instantiate the two listeners and register one
// with the color button and the other with the label button
}
} // close class
class ColorButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
frame.repaint();
}
}
class LabelButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
label.setText(That hurt!);
}
}
|--|--' 1: :|.:: .: -- ------:- l- l- .-.|- '|.-|'
w--'l ---' 1: :|.:: --:-'l .- . ------:- l-
l- '-.--' .-.|- - l- M]6- :|.::
muItipIe Iisteners
Hew 4e yee ]c! zr!|en cvcn!s fer ! we 4|ffcrcn! |e!!ens,
whcn czrh |e!!en ncc4s !e 4e semc!h|n] 4|ffcrcn!!
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 375
WouIdn'f if be wonderfuI if you
couId hove fwo differenf Iisfener cIosses,
buf fhe Iisfener cIosses couId occess fhe
insfonce voriobIes of fhe moin 0UI cIoss,
oImosf os if fhe Iisfener cIosses beIonged
fo fhe ofher cIoss. Then you'd hove fhe besf
of bofh worIds. Yeoh, fhof wouId be dreomy.
8uf if's jusf o fonfosy...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
376 chapter 12
You nr havc onc class ncsicu insiuc anoihci. Ii`s casy.
]usi maIc suic ihai ihc uchniiion loi ihc innci class is
.r.Je ihc cuily liaccs ol ihc ouici class.
|nncr r|zss !e !hc rcsrec|
class MyOuterClass {
class MyInnerClass {
void go() {
}
}
}
8imple inner class:
class MyOuterClass {
private int x;
class MyInnerClass {
void go() {
x = 42;
}
} // close inner class
} // close outer class
-:- '' .: l ---- . .-.|-
- l- ---- :|.::'
nner class using an outer class variable
An innci class gcis a sccial ass io usc ihc ouici class`s siull. E.er
Le ...ne u. Anu ihc innci class can usc ihosc iivaic vaiiallcs
anu mcihous ol ihc ouici class as il ihc vaiiallcs anu mcmlcis
wcic uchncu in ihc innci class. Thai`s whai`s so hanuy aloui innci
classcs-ihcy havc mosi ol ihc lcnchis ol a noimal class, lui wiih
sccial acccss iighis.
Aa :aae: :|ass :aa
ase a|| the ethaJs
aaJ va::al|es aI the
aate: :|ass, evea the
::vate aaes.
The :aae: :|ass gets
ta ase thase va::al|es
aaJ ethaJs ast
as :I the ethaJs
aaJ va::al|es ve:e
Je:|a:eJ v:th:a the
:aae: :|ass.
inner cIasses
|---- :|.:: :
-||]
--:|-:-
] --l-- :|.::
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 377
M
y
I
n
ner o
b
j
e
c
f
Rcmcmlci, whcn wc ialI aloui an innci In acccssing
somcihing in ihc ouici class, wc`ic ically ialIing aloui an
.rnre ol ihc innci class acccssing somcihing in an .rnre ol
ihc ouici class. Bui wL.L insiancc.
Can nr, ailiiiaiy insiancc ol ihc innci class acccss ihc mcihous
anu vaiiallcs ol nr, insiancc ol ihc ouici class.
Ar obe u be .eJ o n e. obe or
Le Len.
n |nncr r|zss |ns!znrc mes! |c !|c4 !e
zn ee!cr r|zss |ns!znrc'.
C
c
l
l
|
n
g
|
n
l
c
u
c
h
w
|
l
h
q
c
u
r
|
n
n
c
r
c
l
a
-
-
O
v
e
r 6
5
,5
3
6
c
o
p
/e
s
s
o
/d
/
T
h
e
n
e
w
b
e
s
ts
e
lle
r fro
m
th
e
a
u
th
o
r o
f '
W
h
o
M
o
v
e
d
m
y
C
h
a
r?
"
0
r
. P
e
ly
M
e
r
p
h
is
m
1
M
y
O
u
fer
o
b
j
e
c
f
Moke on insfonce of
fhe oufer cIoss
2
Moke on insfonce of
fhe inner cIoss, by
using fhe insfonce
of fhe oufer cIoss.
inne
r
MyInner
inf
x
MyOufer
inf
x
:-:.|
--
ou con instantiate an inner instance from code running outs|Je the outer class, but you
have to use a special syntax. Chances are you'll go through your entire 1ava life and never
need to make an inner class from outside, but |ust in case you're interested...
class Foo {
public static void main (String[] args) {
MyOuter outerObj = new MyOuter();
MyOuter.MyInner innerObj = outerObj.new MyInner();
}
}
inner cIass instances
:.|| . --l- -- l-
---- :|.::
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 379
public class TwoButtons {
JFrame frame;
JLabel label;
public static void main (String[] args) {
TwoButtons gui = new TwoButtons ();
gui.go();
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton labelButton = new JButton(Change Label);
labelButton.addActionListener(new LabelListener());
JButton colorButton = new JButton(Change Circle);
colorButton.addActionListener(new ColorListener());
label = new JLabel(I'm a label);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH, colorButton);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.getContentPane().add(BorderLayout.EAST, labelButton);
frame.getContentPane().add(BorderLayout.WEST, label);
frame.setSize(300,300);
frame.setVisible(true);
}
class LabelListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
label.setText(Ouch!);
}
} // close inner class
class ColorListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
frame.repaint();
}
} // close inner class
}
l- -.- 6c| :|.:: --:-'l
-|----l A:l--|:l---- ---
-:l-. - .::- |l:` l- l-
-ll--': |:l---- --:l-.l--
--l-, .:: . --- -:l.-:- -
l- .---.l- |:l---- :|.::
N-- -- -l l- .-
1w6 A:l--|:l----:
- . :-|- :|.:: '
l- ---- :|.:: -l: l- -:- l- '-.--'
-:l.-:- .-.|-, -l--l .- .-
-|:l ------:- l- l- --l-- :|.::
--:l
---- :|.:: ---:
.--l '|.-|'
Now we can get the two-button
code working
Two8uffons
objecf
CoIorLisfener
objecf
LobeILisfener
objecf
-
-l
--
-
-
--
-
-
--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
380 chapter 12
inner cIasses
HeadFirst: What makes inner classes important?
Inner object: Where oo I start? We give you a chance to
implement the same interlace more than once in a class.
Remember, you can`t implement a methoo more than
once in a normal Java class. But using ioo.r classes, each
inner class can implement the oo. interlace, so you can
have all these oiff.r.ot implementations ol the very same
interlace methoos.
HeadFirst: Why woulo you ever ooot to implement the
same methoo twice?
Inner object: Let`s revisit GUI event hanolers. Think
about it... il you want t/r.. buttons to each have a
oillerent event behavior, then use t/r.. inner classes, all
implementing ActionListenerwhich means each class
gets to implement its own actionFerlormeo methoo.
HeadFirst: So are event hanolers the only reason to use
inner classes?
Inner object: Oh, gosh no. Event hanolers are just an
obvious example. Anytime you neeo a separate class, but
still want that class to behave as il it were part ol oot/.r
class, an inner class is the bestano sometimes ol,way
to oo it.
HeadFirst: I`m still conluseo here. Il you want the inner
class to o./o.. like it belongs to the outer class, why have
a separate class in the nrst place? Why woulon`t the inner
class cooe just be io the outer class in the nrst place?
Inner object: I just o.. you one scenario, where you
neeo more than one implementation ol an interlace. But
even when you`re not using interlaces, you might neeo
two oillerent clo. because those classes represent two
oillerent t/io. It`s gooo OO.
HeadFirst: Whoa. Holo on here. I thought a big part ol
OO oesign is about reuse ano maintenance. You know, the
ioea that il you have two separate classes, they can each
be mooineo ano useo inoepenoently, as opposeo to stulnng
it all into one class yaoa yaoa yaoa. But with an ioo.r class,
you`re still just working with one r.ol class in the eno, right?
The enclosing class is the only one that`s reusable ano
separate lrom everybooy else. Inner classes aren`t exactly
reusable. In lact, I`ve hearo them calleo Reuseless
useless over ano over again.
Inner object: Yes it`s true that the inner class is not o
reusable, in lact sometimes not reusable at all, because it`s
intimately tieo to the instance variables ano methoos ol
the outer class. But it
HeadFirst: which only proves my point Il they`re not
reusable, why bother with a separate class? I mean, other
than the interlace issue, which sounos like a workarouno
to me.
Inner object: As I was saying, you neeo to think about
IS-A ano polymorphism.
HeadFirst: OK. Ano I`m thinking about them because...
Inner object: Because the outer ano inner classes
might neeo to pass oiff.r.ot IS-A tests Let`s start with the
polymorphic GUI listener example. What`s the oeclareo
argument type lor the button`s listener registration
methoo? In other woros, il you go to the AFI ano check,
what kino ol t/io ,class or interlace type, oo you have to
pass to the aooActionListener,, methoo?
HeadFirst: You have to pass a listener. Something that
implements a particular listener interlace, in this case
ActionListener. Yeah, we know all this. What`s your point?
Inner object: My point is that polymorphically, you have
a methoo that takes only one particular t,.. Something
that passes the IS-A test lor ActionListener. Butano
here`s the big thingwhat il your class neeos to be an IS-
A ol something that`s a clo type rather than an interlace?
HeadFirst: Woulon`t you have your class just .xt.oo the
class you neeo to be a part ol ? Isn`t that the whole point
ol how subclassing works? Il B is a subclass ol A, then
anywhere an A is expecteo a B can be useo. The whole
pass-a-Dog-where-an-Animal-is-the-oeclareo-type thing.
Inner object: Yes Bingo So now what happens il you
neeo to pass the IS-A test lor two oillerent classes? Classes
that aren`t in the same inheritance hierarchy?
This weeks interview:
Instance of an Inner CIass
1a-a spese3
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 381
HeadFirst: Oh, well you just... hmmm. I think I`m get-
ting it. You can always iol.o.ot more than one interlace,
but you can .xt.oo only o. class. You can only be one kino
ol IS-A when it comes to clo types.
Inner object: Well oone Yes, you can`t be both a Dog
ano a Button. But il you`re a Dog that neeos to some-
times be a Button ,in oroer to pass yoursell to methoos
that take a Button,, the Dog class ,which extenos Animal
so it can`t exteno Button, can have an ioo.r class that acts
on the Dog`s behall as a Button, by extenoing Button,
ano thus wherever a Button is requireo the Dog can
pass his inner Button insteao ol himsell. In other woros,
insteao ol saying x.takeButton,this,, the Dog object calls
x.takeButton,new MyInnerButton,,,.
HeadFirst: Can I get a clear example?
Inner object: Remember the orawing panel we useo,
where we maoe our own subclass ol JFanel? Right now,
that class is a separate, non-inner, class. Ano that`s nne,
because the class ooesn`t neeo special access to the instance
variables ol the main GUI. But what il it oio? What il
we`re ooing an animation on that panel, ano it`s getting its
cooroinates lrom the main application ,say, baseo on some-
thing the user ooes elsewhere in the GUI,. In that case, il
we make the orawing panel an inner class, the orawing
panel class gets to be a subclass ol JFanel, while the outer
class is still lree to be a subclass ol something else.
HeadFirst: Yes I see Ano the orawing panel isn`t reus-
able enough to be a separate class anyway, since what it`s
actually painting is specinc to this one GUI application.
Inner object: Yes You`ve got it
HeadFirst: Gooo. Then we can move on to the nature ol
the r.lotio/i between you ano the outer instance.
Inner object: What is it with you people? Not enough
soroio gossip in a serious topic like polymorphism?
HeadFirst: Hey, you have no ioea how much the public is
willing to pay lor some gooo olo tabloio oirt. So, someone
creates you ano becomes instantly bonoeo to the outer
object, is that right?
Inner object: Yes that`s right. Ano yes, some have
compareo it to an arrangeo marriage. We oon`t have a say
in which object we`re bonoeo to.
HeadFirst: Alright, I`ll go with the marriage analogy.
Can you get a oi.rc. ano remarry something .l.?
Inner object: No, it`s lor lile.
HeadFirst: Whose lile? Yours? The outer object? Both?
Inner object: Mine. I can`t be tieo to any other outer
object. My only way out is garbage collection.
HeadFirst: What about the outer object? Can it be
associateo with any other inner objects?
Inner object: So now we have it. This is what you r.oll,
wanteo. Yes, yes. My so-calleo mate` can have as many
inner objects as it wants.
HeadFirst: Is that like, serial monogamy? Or can it have
them all at the same time?
Inner object: All at the same time. There. Satisneo?
HeadFirst: Well, it ooes make sense. Ano let`s not
lorget, it was ,o extolling the virtues ol multiple
implementations ol the same interlace. So it makes sense
that il the outer class has three buttons, it woulo neeo
three oillerent inner classes ,ano thus three oillerent inner
class objects, to hanole the events. Thanks lor everything.
Here`s a tissue.
He fhinks he's
gof if mode, hoving fwo
inner cIoss objecfs. 8uf we
hove occess fo oII his privofe
dofo, so jusf imogine fhe domoge
we couId do...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
382 chapter 12
Wc saw why innci classcs aic hanuy loi cvcni lisicncis, lccausc
you gci io imlcmcni ihc samc cvcni-hanuling mcihou moic
ihan oncc. Bui now wc`ll looI ai how usclul an innci class is whcn
uscu as a sulclass ol somcihing ihc ouici class uocsn`i cxicnu. In
oihci woius, whcn ihc ouici class anu innci class aic in uillcicni
inhciiiancc iiccs!
Oui goal is io maIc a simlc animaiion, whcic ihc ciiclc movcs
acioss ihc sciccn liom ihc uci lcli uown io ihc lowci iighi.
0s|n] zn |nncr r|zss fer zn|mz!|en
:l.-l
-:
How simple animation works
1 Poinf on objecf of o porficuIor x ond y coordinofe
g.llOval(20,50,100,100);
io -|: --- l- |-l,
-o -|: --- l- l-
2 Pepoinf fhe objecf of o differenf x ond y coordinofe
g.llOval(25,55,100,100);
i- -|: --- l- |-l, --
-|: --- l- l-
|l- --:l --- . |ll|-
--- .- l- l- -l`
3 Pepeof fhe previous sfep wifh chonging x ond y voIues
for os Iong os fhe onimofion is supposed fo confinue.
(-,- a,- |
oa|| qa--(:|-
start nish
start nish
X +?
Y +?
start nish
X
Y
X
Y
start nish
start nish
X
Y
start nish
X
Y
X
Y
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
386 chapter 12
CaJe kit:hea
Iet's a|e a asi: viJea. he'|| ase Java-geae:ateJ :aaJa
g:ahi:s that |ee tie vith the asi: leats.
A|aag the vay ve'|| :egiste: laaJ |istea Ia:I a aev |iaJ aI
aaa-6l! eveat, t:igge:eJ ly the asi: itse|I.
-.l --- -.l l-- -.l l---
-.l ---
------, l: .-l : .|| -l--.| B-l -- l- l': -- -- ]--
A- ]--'|| |- l A- ]-- :.- -:- l l- ---:: --|-
|6, :---, l -l --- --|] -- --|- -- .-- --.||] -.:] l- ---::,
-l :l||`
Code Kitchen
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 387
OK, maylc noi a music viuco, lui wc w.II maIc
a iogiam ihai uiaws ianuom giahics on ihc
sciccn wiih ihc lcai ol ihc music. In a nuishcll,
ihc iogiam lisicns loi ihc lcai ol ihc music
anu uiaws a ianuom giahic iccianglc wiih cach
lcai.
Thai liings u somc ncw issucs loi us. So lai,
wc`vc lisicncu loi only GUI cvcnis, lui now
wc nccu io lisicn loi a aiiiculai Iinu ol MIDI
cvcni. Tuins oui, lisicning loi a non-GUI cvcni is
|usi liIc lisicning loi GUI cvcnis: you imlcmcni
a lisicnci inicilacc, icgisici ihc lisicnci wiih an
cvcni souicc, ihcn sii lacI anu waii loi ihc cvcni
souicc io call youi cvcni-hanulci mcihou ihc
mcihou uchncu in ihc lisicnci inicilacc).
Thc simlcsi way io lisicn loi ihc lcai ol ihc
music woulu lc io icgisici anu lisicn loi ihc
aciual MIDI cvcnis, so ihai whcncvci ihc
scqucncci gcis ihc cvcni, oui couc will gci ii
ioo anu can uiaw ihc giahic. Bui... ihcic`s a
iollcm. A lug, aciually, ihai won`i lci us lisicn
loi ihc MIDI cvcnis we`.e maIing ihc oncs loi
NOTE ON).
So wc havc io uo a liiilc woiI-aiounu. Thcic
is anoihci iyc ol MIDI cvcni wc can lisicn
loi, callcu a ConiiollciEvcni. Oui soluiion
is io icgisici loi ConiiollciEvcnis, anu ihcn
maIc suic ihai loi cvciy NOTE ON cvcni,
ihcic`s a maiching ConiiollciEvcni hicu ai
ihc samc lcai`. How uo wc maIc suic ihc
ConiiollciEvcni is hicu ai ihc samc iimc. Wc
auu ii io ihc iiacI |usi liIc ihc oihci cvcnis! In
oihci woius, oui music scqucncc gocs liIc ihis:
BEAT 1 - NOTE ON, CONTROIIER EVENT
BEAT 2 - NOTE OII
BEAT S - NOTE ON, CONTROIIER EVENT
BEAT 4 - NOTE OII
anu so on.
Bcloic wc uivc inio ihc lull iogiam, ihough,
lci`s maIc ii a liiilc casici io maIc anu auu MIDI
mcssagcs/cvcnis sincc in L. iogiam, wc`ic
gonna maIc a loi ol ihcm.
I|s!cn|n] fer z nen-00| cvcn!
1 Moke o series of MIDI messoges/
evenfs fo pIoy rondom nofes on o piono
(or whofever insfrumenf you choose)
What the music art program
needs to do:
2 Pegisfer o Iisfener for fhe evenfs
3 Sforf fhe sequencer pIoying
4 Eoch fime fhe Iisfener's evenf
hondIer mefhod is coIIed, drow o
rondom recfongIe on fhe drowing
poneI, ond coII repoinf.
1 Version One: Code fhof simpIifes mok-
ing ond odding MIDI evenfs, since we'II
be moking o Iof of fhem.
We'll build it in three iterations:
2 Version Two: Pegisfer ond Iisfen for
fhe evenfs, buf wifhouf grophics.
Prinfs o messoge of fhe commond-Iine
wifh eoch beof.
4 Version Three: The reoI deoI. Adds
grophics fo version fwo.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
388 chapter 12
ShortMessage a = new ShortMessage();
a.setMessage(144, 1, note, 100);
MidiEvent noteOn = new MidiEvent(a, 1);
track.add(noteOn);
ShortMessage b = new ShortMessage();
b.setMessage(128, 1, note, 100);
MidiEvent noteOff = new MidiEvent(b, 16);
track.add(noteOff);
Righi now, maIing anu auuing mcssagcs anu
cvcnis io a iiacI is icuious. Ioi cach mcssagc,
wc havc io maIc ihc mcssagc insiancc in ihis
casc, ShoiiMcssagc), call sciMcssagc), maIc a
MiuiEvcni loi ihc mcssagc, anu auu ihc cvcni
io ihc iiacI. In lasi chaici`s couc, wc wcni
ihiough cach sic loi cvciy mcssagc. Thai
mcans cighi lincs ol couc |usi io maIc a noic
lay anu ihcn sio laying! Ioui lincs io auu a
NOTE ON cvcni, anu loui lincs io auu a NOTE
OII cvcni.
n czs|cr wzy !e mzkc
mcssz]cs / cvcn!s
1 Moke o messoge insfonce
ShortMessage rst = new ShortMessage();
Things that have to happen for
each event:
2 CoII sefMessoge() wifh fhe insfrucfions
rst.setMessage(192, 1, instrument, 0)
3 Moke o MidiEvenf insfonce for fhe messoge
MidiEvent noteOn = new MidiEvent(rst, 1);
4 Add fhe evenf fo fhe frock
track.add(noteOn);
public static MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) {
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);
}catch(Exception e) { }
return event;
}
Let's build a static utility method that
makes a message and returns a MidiEvent
l- --- .-----l:
-- l- --::.-
1- ---l 'l:' --
w+!N l: --::.-
:--| .--
-.- l- --::.- .- l- ---l, -:-
l- --l- .-.--l--:
---' A --l- -l - .-.--l--:
--l--- l- ---l |. M!--l .||
|-.- - -l l- --::.-`
utiIity method for events
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 389
import javax.sound.midi.*;
public class MiniMusicPlayer1 {
public static void main(String[] args) {
try {
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
for (int i = 5; i < 61; i+= 4) {
track.add(makeEvent(144,1,i,100,i));
track.add(makeEvent(128,1,i,100,i + 2));
} // end loop
sequencer.setSequence(seq);
sequencer.setTempoInBPM(220);
sequencer.start();
} catch (Exception ex) {ex.printStackTrace();}
} // close main
public static MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) {
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);
}catch(Exception e) { }
return event;
}
} // close class
-.- |.- ---` . :----:--
-.- . :----:-
.- . l-.:
-.- . --: - ---l: l- -.- l- --l-: --
-- - |--- .-- --l- - l- .-- --l- ||`
--'l ---l l- -
--l
:.|| --- --- -.-!--l|` --l- l- -.- l-
--::.- .- ---l, l-- . l- --:-|l |l-
M!--l --l---- --- -.-!--l|`` l-
l- l-.: 1-:- .-- N61! 6N ||++` .-
N61! 6|| ||i` .-:
:l.-l l -----
Thcic`s no cvcni hanuling oi giahics hcic, |usi a scqucncc ol 1
noics ihai go u ihc scalc. Thc oini ol ihis couc is simly io lcain
how io usc oui ncw maIcEvcni) mcihou. Thc couc loi ihc ncxi
iwo vcisions is much smallci anu simlci ihanIs io ihis mcihou.
Irzmp|c: hew !e esc !hc ncw s!z!|r
mzkcIvcn!|I mc!he4
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
390 chapter 12
import javax.sound.midi.*;
public class MiniMusicPlayer2 implements ControllerEventListener {
public static void main(String[] args) {
MiniMusicPlayer2 mini = new MiniMusicPlayer2();
mini.go();
}
public void go() {
try {
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
int[] eventsIWant = {127};
sequencer.addControllerEventListener(this, eventsIWant);
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
for (int i = 5; i < 60; i+= 4) {
track.add(makeEvent(144,1,i,100,i));
track.add(makeEvent(176,1,127,0,i));
track.add(makeEvent(128,1,i,100,i + 2));
} // end loop
sequencer.setSequence(seq);
sequencer.setTempoInBPM(220);
sequencer.start();
} catch (Exception ex) {ex.printStackTrace();}
} // close
public void controlChange(ShortMessage event) {
System.out.println(la);
}
public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) {
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);
}catch(Exception e) { }
return event;
}
} // close class
Code fhof's differenf from fhe previous
version is highIighfed in groy. (ond we're
nof running if oII wifhin moin() fhis fime)
w- --- l- |:l-- -- c--l--||--!--l:,
:- -- -|----l l- |:l---- -l--.:-
-:l-- -- ---l: -l l- :----:--
1- ---l --:l-.l-- --l- l.-: l-
|:l---- ANl .- -l .--.] ----:--l-
l- |:l - c--l--||--!--l: ]-- -.-l
w- -.-l --|] --- ---l, +|i7
+---': -- -- : - l- -.l ~~ -- -:--l --- 6wN c--l--||--!--l ||7| :.]: l- ---l l]- : c--l--||--!--l` -l .- .-----l --
---l ----- +|i7 1: ---l -|| - N61+~ |N6' w- -l l - )c1 :- l.l -- :.- -l .- ---l -.: l-- . --l- : |.]- |- -l-- ---:, l: :-|- ---:- : :- l.l :---l- -||
-- l.l w! :.- |:l-- -- |-- :.-'l |:l-- -- N61! 6N/6|| ---l:` N-l- l.l --'-- -.- l: ---l .-- .l l- AM! l: .:
l- N61! 6N - --- l- N61! 6N ---l .--:, --'|| --- .--l l -:.-:- 6c ---l
-|| -- .l l- :.-- l--
1- ---l .-|-- --l- |--- l- c--l--||--~
!--l |:l---- -l--.:-` !.: l-- -- -l l-
---l, --'|| --l |.' l- l- :---.-~|--
Vcrs|en Iwe: rc]|s!cr|n] zn4 ]c!!|n] 0en!re||crIvcn!s
controIIer events
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 391
This hnal vcision luilus on vcision iwo ly auuing ihc GUI aiis. Wc luilu a
liamc, auu a uiawing ancl io ii, anu cach iimc wc gci an cvcni, wc uiaw a
ncw iccianglc anu icaini ihc sciccn. Thc only oihci changc liom vcision
iwo is ihai ihc noics lay ianuomly as ooscu io simly moving u ihc
scalc.
Thc mosi imoiiani changc io ihc couc lcsiucs luiluing a simlc GUI)
is ihai wc maIc ihc uiawing ancl imlcmcni ihc ConiiollciEvcniIisicnci
iaihci ihan ihc iogiam iiscll. So whcn ihc uiawing ancl an innci class)
gcis ihc cvcni, ii Inows how io iaIc caic ol iiscll ly uiawing ihc iccianglc.
Comlcic couc loi ihis vcision is on ihc ncxi agc.
Vcrs|en Ihrcc: 4rzw|n] ]rzph|rs |n !|mc w| !h !hc mes|r
class MyDrawPanel extends JPanel implements ControllerEventListener {
boolean msg = false;
public void controlChange(ShortMessage event) {
msg = true;
repaint();
}
public void paintComponent(Graphics g) {
if (msg) {
Graphics2D g2 = (Graphics2D) g;
int r = (int) (Math.random() * 250);
int gr = (int) (Math.random() * 250);
int b = (int) (Math.random() * 250);
g.setColor(new Color(r,gr,b));
int ht = (int) ((Math.random() * 120) + 10);
int width = (int) ((Math.random() * 120) + 10);
int x = (int) ((Math.random() * 40) + 10);
int y = (int) ((Math.random() * 40) + 10);
g.llRect(x,y,ht, width);
msg = false;
} // close if
} // close method
} // close inner class
The drawing panel inner class:
1- -.-- .--| : . |:l----
w- :-l . |. l- .|:-, .- --'|| :-l l
l- l--- --|] --- -- -l .- ---l
w- -l .- ---l, :- -- :-l l- |. l-
l--- .- :.|| --.-l|`
w- .- l- -:- . |. -:.-:- 61+! l-: -l l--- . --.-l|`, .- -- -.-l l- .-l 6N|/ --- l---': . c--l--||--!--l
1- --:l : :-- l- ----.l-
. -.--- :-|-- .- .-l .
:--~-.--- --:l.-|-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
392 chapter 12
import javax.sound.midi.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
public class MiniMusicPlayer3 {
static JFrame f = new JFrame(My First Music Video);
static MyDrawPanel ml;
public static void main(String[] args) {
MiniMusicPlayer3 mini = new MiniMusicPlayer3();
mini.go();
} // close method
public void setUpGui() {
ml = new MyDrawPanel();
f.setContentPane(ml);
f.setBounds(30,30, 300,300);
f.setVisible(true);
} // close method
public void go() {
setUpGui();
try {
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
sequencer.addControllerEventListener(ml, new int[] {127});
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
int r = 0;
for (int i = 0; i < 60; i+= 4) {
r = (int) ((Math.random() * 50) + 1);
track.add(makeEvent(144,1,r,100,i));
track.add(makeEvent(176,1,127,0,i));
track.add(makeEvent(128,1,r,100,i + 2));
} // end loop
sequencer.setSequence(seq);
sequencer.start();
sequencer.setTempoInBPM(120);
} catch (Exception ex) {ex.printStackTrace();}
} // close method
+,-+ :+ ,-+:.|
This is fhe compIefe code Iisfing for Version
Three. If buiIds direcfoy on Version Two. Try
fo onnofofe if yourseIf, wifhouf Iooking of fhe
previous poges.
MiniMusicPIayer3 code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
getting gui
you are here 393
public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) {
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);
}catch(Exception e) { }
return event;
} // close method
class MyDrawPanel extends JPanel implements ControllerEventListener {
boolean msg = false;
public void controlChange(ShortMessage event) {
msg = true;
repaint();
}
public void paintComponent(Graphics g) {
if (msg) {
Graphics2D g2 = (Graphics2D) g;
int r = (int) (Math.random() * 250);
int gr = (int) (Math.random() * 250);
int b = (int) (Math.random() * 250);
g.setColor(new Color(r,gr,b));
int ht = (int) ((Math.random() * 120) + 10);
int width = (int) ((Math.random() * 120) + 10);
int x = (int) ((Math.random() * 40) + 10);
int y = (int) ((Math.random() * 40) + 10);
g.llRect(x,y,ht, width);
msg = false;
} // close if
} // close method
} // close inner class
} // close class
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
394 chapter 12
A bunch of 1ava hot-shots, in full costume, are playing the party game "who
am |I They give you a clue, and you try to guess who they are, based on
what they say. Assume they always tell the truth about themselves. |f they
happen to say something that could be true for more than one guy, then
write down all for whom that sentence applies. Pill in the blanks next to the
sentence with the names of one or more attendees.
7onight's attendees:
Any of the charming personaIities from this chapter just
might show upl
I got the whoIe GUI, in my hands.
Every event type has one of these.
The Iistener's key method.
This method gives JFrame its size.
You add code to this method but never caII it.
When the user actuaIIy does something, it's an _____ .
Most of these are event sources.
I carry data back to the Iistener.
An addXxxListener( ) method says an object is an _____ .
How a Iistener signs up.
The method where aII the graphics code goes.
I'm typicaIIy bound to an instance.
The 'g' in (Graphics g), is reaIIy of cIass.
The method that gets paintComponent( ) roIIing.
The package where most of the Swingers reside.
exercise: Who Am I
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 395
[[ ]zvz |j] n ([j, zg ,n(, z
e]( ,ae |j]. (a j j, ( ]zy
ej] zn] ](jn w[([ ([j, |j]
wj]] ej]. ]| j( wn'( ej], [w
wa]] ya |jy j(, zn] j| j( ],
ej], w[z( wa]] j( ]/
import avax.swing.*,
import ava.awt.event.*,
import ava.awt.*,
class InnerButton {
JFrame frame,
JButton b,
public static void main{String args| {
InnerButton gui = new InnerButton{|,
gui.go{|,
}
public void go{| {
frame = new JFrame{|,
frame.setDefaultCloseOperation{
JFrame.EXIT_ON_CLOSE|,
b = new JButton{"A"|,
b.addActionListener{|,
frame.getContentPane{|.add{
BorderLayout.SOUTH, b|,
frame.setSize{200,l00|,
frame.setVisible{true|,
}
class BListener extends ActionListener {
public void actionPerformed{ActionEvent e| {
if {b.getText{|.equals{"A"|| {
b.setText{"B"|,
} else {
b.setText{"A"|,
}
}
}
}
] ge eomgj|e;
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
our is to take code snippets from
the pool and place them into the blank
lines in the code. ou may use the
same snippet more than once,
and you won't need to use all the
snippets. our is to make a
class that will compile and run
and produce the output listed.
Note: ach snippet
from the pooI can be
used more than oncel
Dutput
drawP.setSize(500,270)
frame.setSize(500,270)
panel.setSize(500,270)
x++
y++
Thc Amazing, ShiinIing, Bluc Rccianglc.
This iogiam will iouucc a lluc
iccianglc ihai will shiinI anu shiinI anu
uisacai inio a hclu ol whiic.
g.setColor(blue)
g.setColor(white)
g.setColor(Color.blue)
g.setColor(Color.white)
g.fillPect(x,y,x-500,y-250)
g.fillPect(x,y,500-x`2,250-y`2)
g.fillPect(500-x`2,250-y`2,x,y)
g.fillPect(0,0,250,500)
g.fillPect(0,0,500,250)
g
draw
frame
panel
i++
i++, y++
i++, y++, x++
Animate frame new Animate()
MyDrawP drawP new MyDrawP()
ContentPane drawP new ContentPane() drawP.paint()
draw.repaint()
drawP.repaint()
puzzIe: PooI PuzzIe
import avax.swing.*,
import ava.awt.*,
public class Animate {
int x = l,
int y = l,
public static void main {String args| {
Animate gui = new Animate {|,
gui.go{|,
}
public void go{| {
JFrame _________ = new JFrame{|,
frame.setDefaultCloseOperation{
JFrame.EXIT_ON_CLOSE|,
______________________________________,
_________.getContentPane{|.add{drawP|,
__________________________,
_________.setVisible{true|,
for {int i=0, i<l24, _______________| {
_____________________,
_____________________,
try {
Thread.sleep{50|,
} catch{Exception ex| { }
}
}
class MyDrawP extends JPanel {
public void paintComponent {Graphic
_________| {
__________________________________,
__________________________________,
__________________________________,
__________________________________,
}
}
}
396 chapter 12
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
getting gui
you are here 397
import avax.swing.*,
import ava.awt.event.*,
import ava.awt.*,
class InnerButton {
JFrame frame,
JButton b,
public static void main{String args| {
InnerButton gui = new InnerButton{|,
gui.go{|,
}
public void go{| {
frame = new JFrame{|,
frame.setDefaultCloseOperation{
JFrame.EXIT_ON_CLOSE|,
b = new JButton{"A"|,
b.addActionListener{ ncw BI|s!cncr| I |,
frame.getContentPane{|.add{
BorderLayout.SOUTH, b|,
frame.setSize{200,l00|,
frame.setVisible{true|,
}
class BListener |mp|cmcn!s ActionListener {
public void actionPerformed{ActionEvent e| {
if {b.getText{|.equals{"A"|| {
b.setText{"B"|,
} else {
b.setText{"A"|,
}
}
}
}
The oddAcfionLisfener( )
mefhod fokes o cIoss fhof
impIemenfs fhe AcfionLis-
fener inferfoce
AcfionLisfener is on
inferfoce, inferfoces
ore impIemenfed, nof
exfended
] ge eomgj|e;
Once fhis code
is fxed, if wiII
creofe o 0UI wifh
o buffon fhof
foggIes befween
A ond 8 when you
cIick if.
I goi ihc wholc GUI, in my hanus. JFrome
Evciy cvcni iyc has onc ol ihcsc. Iisfener inferfoce
Thc lisicnci`s Icy mcihou. ocfionPerformed( )
This mcihou givcs ]Iiamc iis sizc. sefSi;e( )
You auu couc io ihis mcihou lui
ncvci call ii. poinfComponenf( )
Whcn ihc usci aciually uocs
somcihing, ii`s an ____ evenf
Mosi ol ihcsc aic cvcni souiccs. swing componenfs
I caiiy uaia lacI io ihc lisicnci. evenf objecf
An auuXxxIisicnci ) mcihou
says an ol|cci is an ___ evenf source
How a lisicnci signs u. oddAcfionLisfener( )
Thc mcihou whcic all ihc
giahics couc gocs. poinfComponenf( )
I`m iyically lounu io an insiancc. inner cIoss
Thc g` in Giahics g), is
ically ol ihis class. 0rophicsZd
Thc mcihou ihai gcis
ainiComoncni ) iolling. repoinf( )
Thc acIagc whcic mosi ol ihc
Swingcis icsiuc. jovox.swing
[yej, ]a(jn,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
398 chapter 12
import avax.swing.*,
import ava.awt.*,
public class Animate {
int x = l,
int y = l,
public static void main {String args| {
Animate gui = new Animate {|,
gui.go{|,
}
public void go{| {
JFrame frome = new JFrame{|,
frame.setDefaultCloseOperation{
JFrame.EXIT_ON_CLOSE|,
MyDrowP drowP ~ new MyDrowP(),
frome.getContentPane{|.add{drawP|,
frome.sefSi;e(b00,Z70),
frome.setVisible{true|,
for {int i = 0, i < l24, i++,x++,y++ | {
x++,
drowP.repoinf(),
try {
Thread.sleep{50|,
} catch{Exception ex| { }
}
}
class MyDrawP extends JPanel {
public void paintComponent{Graphics g | {
g.sefCoIor(CoIor.whife),
g.fIIPecf(0,0,b00,Zb0),
g.sefCoIor(CoIor.bIue),
g.fIIPecf(x,y,b00-x*Z,Zb0-y*Z),
}
}
}
Thc Amazing, ShiinIing, Bluc
Rccianglc.
puzzIe answers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
this is a new chapter 399
13 using swing
Swing is easy. Unless you actually cote where things end up on the screen. Swing code
lools easy, but then you compile it, run it, look at it and think, "hey, thots not supposed to go
thete. The thing that makes it eosy to coJe is the thing that makes it hotJ to conttolthe
Layout Manager. Layout Manager ob|ects control the size and location of the widgets in a
1ava GU|. They do a ton of work on your behalf, but you won't always like the results. ou want
two buttons to be the same size, but they aren't. ou want the text field to be three inches long,
but it's nine. Or one. And unJet the label instead of next to it. 8ut with a little work, you can get
layout managers to submit to your will. |n this chapter, we'll work on our Swing and in addition
to layout managers, we'll learn more about widgets. we'll make them, display them (where we
choose), and use them in a program. |t's not looking too good for Suzy.
Why won'f
fhe boII go where wonf
if fo go7 (Iike, smock in Su;y
Smifh's foce) I've goffo Ieorn
fo confroI if.
Work on Your
8wing
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
400 chapter 13
is ihc moic coiicci icim loi whai wc`vc lccn calling a w.Je.
Thc L.r you ui in a GUI. TLe L.r n ue. ee nrJ .re.n w.L. Tcxi
hclus, luiions, sciollallc lisis, iauio luiions, cic. aic all comoncnis. In
laci, ihcy all cxicnu javax.swing.JComponent.
components and containers
8w|n] rempencn!s
In Swing, viiiually nII comoncnis aic caallc ol holuing oihci
comoncnis. In oihci woius, ,ou nr .I u nbou nr,L.r .ro nr,L.r
eIe. Bui mosi ol ihc iimc, you`ll auu ue. .re.n..e comoncnis such as
luiions anu lisis inio bnI.ourJ comoncnis such as liamcs anu ancls.
Alihough ii`s o.bIe io ui, say, a ancl insiuc a luiion, ihai`s iciiy
wciiu, anu won`i win you any usaliliiy awaius.
Wiih ihc cxcciion ol ]Iiamc, ihough, ihc uisiinciion lciwccn .re.n..e
comoncnis anu bnI.ourJ comoncnis is aiiihcial. A ]Pancl, loi
cxamlc, is usually uscu as a lacIgiounu loi giouing oihci comoncnis,
lui cvcn a ]Pancl can lc iniciaciivc. ]usi as wiih oihci comoncnis, you
can icgisici loi ihc ]Pancl`s cvcnis incluuing mousc clicIs anu IcysiioIcs.
0empencn!s rzn |c ncs!c4
Four steps to making a GU {review}
JFrame frame = new JFrame();
Moke o window (o JFrome)
JButton button = new JButton(click me);
frame.getContentPane().add(BorderLayout.EAST, button);
1
Moke o componenf (buffon, fexf feId, efc.) 2
Add fhe componenf fo fhe frome 3
frame.setSize(300,300);
frame.setVisible(true);
DispIoy if (give if o si;e ond moke if visibIe) 4
Put interactive components: nto background components:
)B-ll--
)c-:B-
)1-l|-|
)|-.--
)|.--|
A v:Jget :s te:ha::a||y
a Sv:ag Caaaeat.
A|ast eve:y th:ag
yaa :aa st::| :a a
6l! exteaJs I:a
avax.sv:ag.JCaaaeat.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 401
Izyee! Mznz]crs
|.--| A': |.]--l -.-.--
:--l--|: l- :-- .-
|.:----l - |.--| B
As o Ioyouf monoger,
I'm in chorge of fhe si;e
ond pIocemenf of your componenfs.
In fhis 0UI, I'm fhe one who decided
how big fhese buffons shouId be, ond
where fhey ore reIofive fo eoch
ofher ond fhe frome.
A layoui managci is a ]ava ol|cci associaicu
wiih a aiiiculai comoncni, almosi always a
bnI.ourJ comoncni. Thc layoui managci
coniiols ihc comoncnis coniaincu w.L.r ihc
comoncni ihc layoui managci is associaicu
wiih. In oihci woius, il a liamc holus a ancl,
anu ihc ancl holus a luiion, ihc ancl`s layoui
managci coniiols ihc sizc anu laccmcni ol
ihc luiion, whilc ihc liamc`s layoui managci
coniiols ihc sizc anu laccmcni ol ihc
ancl. Thc luiion, on ihc oihci hanu,
uocsn`i nccu a layoui managci lccausc ihc
luiion isn`i holuing oihci comoncnis.
Il a ancl holus hvc ihings, cvcn il ihosc
hvc ihings cach havc ihcii own layoui
managcis, ihc sizc anu locaiion ol ihc hvc
ihings in ihc ancl aic all coniiollcu ly ihc
ancl`s layoui managci. Il ihosc hvc ihings,
in iuin, holu oLe. ihings, ihcn ihosc oLe.
ihings aic laccu accoiuing io ihc layoui
managci ol ihc ihing holuing ihcm.
Whcn wc say LoIJ wc ically mcan nJJ as in, a
ancl LoIJ a luiion lccausc ihc luiion was
nJJeJ io ihc ancl using somcihing liIc:
myPanel.add(button);
Iayoui managcis comc in scvcial uavois, anu
cach lacIgiounu comoncni can havc iis own
layoui managci. Iayoui managcis havc ihcii
own olicics io lollow whcn luiluing a layoui.
Ioi cxamlc, onc layoui managci mighi insisi
ihai all comoncnis in a ancl musi lc ihc samc
sizc, aiiangcu in a giiu, whilc anoihci layoui
managci mighi lci cach comoncni choosc iis
own sizc, lui siacI ihcm vciiically. Hcic`s an
cxamlc ol ncsicu layouis:
PoneI A
PoneI 8
buffon I
buffon Z
buffon 3
|
.--| B
': |.]--l
-
.-.--
:--l
--|: l
- :-
- .-
|.:--
--l
-
l
- l
--- -l
l
--:
|.--| A': |.]--l -.-.-- .: N61+|N6 l-
:.] .--l l- l--- -ll--: 1- --.-:]
- :--l--| : --|] --- |--|-|.--| A': |.]--l
-.-.-- :--l--|: --|] l- l-: .- --:l|]
l- |.--| A, .- --: --l :--l--| .-]l-
--:l- -l- l-:- .- :------l:
JPanel panelA = new JPanel();
JPanel panelB = new JPanel();
panelB.add(new JButton(button 1));
panelB.add(new JButton(button 2));
panelB.add(new JButton(button 3));
panelA.add(panelB);
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
402 chapter 13
Dillcicni layoui managcis havc uillcicni olicics loi aiianging
comoncnis liIc, aiiangc in a giiu, maIc ihcm all ihc samc sizc,
siacI ihcm vciiically, cic.) lui ihc comoncnis lcing laycu oui uo
gci ai lcasi oe small say in ihc maiici. In gcncial, ihc ioccss ol
laying oui a lacIgiounu comoncni looIs somcihing liIc ihis:
Hew 4ecs !hc |zyee! mznz]cr 4cr|4c!
P|ffcrcn! |zyee! mznz]crs hzvc 4|ffcrcn! pe||r|cs
Moke o poneI ond odd fhree buffons fo if. 1
The poneI's Ioyouf monoger osks eoch buffon how big
fhof buffon prefers fo be.
Add fhe poneI fo o frome. 4
2
The poneI's Ioyouf monoger uses ifs Ioyouf poIicies fo decide
whefher if shouId respecf oII, porf, or none of fhe buffons'
preferences.
3
The frome's Ioyouf monoger osks fhe poneI how big fhe poneI
prefers fo be.
5
The frome's Ioyouf monoger uses ifs Ioyouf poIicies fo decide
whefher if shouId respecf oII, porf, or none of fhe poneI's
preferences.
6
Lef's see here... fhe
frsf buffon wonfs fo be
30 pixeIs wide, ond fhe fexf feId
needs b0, ond fhe frome is Z00 pixeIs
wide ond I'm supposed fo orronge
everyfhing verficoIIy...
|.]--l
-
.-.--
A layout scenario:
Somc layoui managcis icscci ihc sizc ihc comoncni wanis io
lc. Il ihc luiion wanis io lc S0 ixcls ly 0 ixcls, ihai`s whai ihc
layoui managci allocaics loi ihai luiion. Oihci layoui managcis
icscci only aii ol ihc comoncni`s iclciicu sizc. Il ihc luiion
wanis io lc S0 ixcls ly 0 ixcls, ii`ll lc S0 ixcls ly howcvci
wiuc ihc luiion`s lacIgiounu nreI is. Siill oihci layoui managcis
icscci ihc iclcicncc ol only ihc In.e ol ihc comoncnis
lcing laycu oui, anu ihc icsi ol ihc comoncnis in ihai ancl
aic all mauc ihai samc sizc. In somc cascs, ihc woiI ol ihc layoui
managci can gci vciy comlcx, lui mosi ol ihc iimc you can
hguic oui whai ihc layoui managci will iolally uo, oncc you gci
io Inow ihai layoui managci`s olicics.
Iayout managers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
using swing
you are here 403
Ihc B|] Ihrcc |zyee! mznz]crs:
|er4cr, f|ew, zn4 |er.
BorderLayout
A 8orderLoyouf monoger divides o bockground
componenf info fve regions. You con odd onIy one
componenf per region fo o bockground confroIIed
by o 8orderLoyouf monoger. Componenfs Ioid ouf
by fhis monoger usuoIIy don'f gef fo hove fheir
preferred si;e. orderLuyout is the defuuIt Iuyout
munuger for u frume|
FlowLayout
A FIowLoyouf monoger ocfs kind of Iike o word
processor, excepf wifh componenfs insfeod of
words. Eoch componenf is fhe si;e if wonfs fo be,
ond fhey're Ioid ouf Ieff fo righf in fhe order fhof
fhey're odded, wifh "word-wrop" furned on. So
when o componenf won'f ff hori;onfoIIy, if drops
fo fhe nexf "Iine" in fhe Ioyouf. FIowLuyout is the
defuuIt Iuyout munuger for u puneI|
BoxLayout
A 8oxLoyouf monoger is Iike FIowLoyouf in fhof
eoch componenf gefs fo hove ifs own si;e, ond
fhe componenfs ore pIoced in fhe order in which
fhey're odded. 8uf, unIike FIowLoyouf, o 8oxLoyouf
monoger con sfock fhe componenfs verficoIIy (or
hori;onfoIIy, buf usuoIIy we're jusf concerned wifh
verficoIIy). If's Iike o FIowLoyouf buf insfeod of
hoving oufomofic 'componenf wropping', you con
inserf o sorf of 'componenf refurn key' ond force
fhe componenfs fo sforf o new Iine.
--- :------l
-- ----
:------l: .- |-l
l- -l, --.- l- .
--- |-- --- ----
:------l: .- l-
l- -ll--, --- -- '|--'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
404 chapter 13
BorderLayout cares
about five regions:
east, west, north,
south, and center
import javax.swing.*;
import java.awt.*;
public class Button1 {
public static void main (String[] args) {
Button1 gui = new Button1();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
JButton button = new JButton(click me);
frame.getContentPane().add(BorderLayout.EAST, button);
frame.setSize(200,200);
frame.setVisible(true);
}
}
B----|.]--l : - ...-l .:.-
:-:] l- ----
Let's add a button to the east region:
border Iayout
8f8l 88f00ll
How did fhe 8orderLoyouf monoger come up wifh
fhis si;e for fhe buffon7
Whof ore fhe focfors fhe Ioyouf monoger hos fo
consider7
Why isn'f if wider or foIIer7
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 405
Since if's in fhe eosf
region of o border Ioyouf,
I'II respecf ifs preferred widfh. 8uf
I don'f core how foII if wonfs fo be,
if's gonno be os foII os fhe frome,
becouse fhof's my poIicy.
public void go() {
JFrame frame = new JFrame();
JButton button = new JButton(click like you mean it);
frame.getContentPane().add(BorderLayout.EAST, button);
frame.setSize(200,200);
frame.setVisible(true);
}
Watch what happens when we give
the button more characters...
w
- :.-- --|] l- l-l
-- l- -ll--
8
u
f
fon o
b
j
e
c
f
Firsf, I osk fhe
buffon for ifs
preferred si;e.
I hove o Iof of words
now, so I'd prefer fo be
o0 pixeIs wide ond Zb
pixeIs foII.
8
u
f
fon o
b
j
e
c
f
Mexf fime
I'm goin' wifh ow
Ioyouf. Then I gef
EVEPYTHIM0 I
wonf.
1
- -ll-- -l:
l: ------ -l,
-l --l -l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
406 chapter 13
border Iayout
public void go() {
JFrame frame = new JFrame();
JButton button = new JButton(There is no spoon...);
frame.getContentPane().add(BorderLayout.NORTH, button);
frame.setSize(200,200);
frame.setVisible(true);
}
Let's try a button in the NORTH region
public void go() {
JFrame frame = new JFrame();
JButton button = new JButton(Click This!);
Font bigFont = new Font(serif, Font.BOLD, 28);
button.setFont(bigFont);
frame.getContentPane().add(BorderLayout.NORTH, button);
frame.setSize(200,200);
frame.setVisible(true);
}
Now let's make the button ask to be taller
How do we do fhof7 The buffon is oIreody os wide
os if con ever be-os wide os fhe frome. 8uf we
con fry fo moke if foIIer by giving if o bigger fonf.
1
- -ll-- : .: l.|| .: l
-.-l: l- -, -l .: -- .:
l- -.-
-
1- -l :l.]: l- :.--, -l ---
l- -ll-- : l.||-- 1- ---l
---- :l--l:- l- .::---.l-
l- -ll--': --- ------ -l
A
-- --l -|| --:- l-
-.-
- l- .||-:.l- -
--- :.:-
-- l- -ll--': -l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 407
public void go() {
JFrame frame = new JFrame();
JButton east = new JButton(East);
JButton west = new JButton(West);
JButton north = new JButton(North);
JButton south = new JButton(South);
JButton center = new JButton(Center);
frame.getContentPane().add(BorderLayout.EAST, east);
frame.getContentPane().add(BorderLayout.WEST, west);
frame.getContentPane().add(BorderLayout.NORTH, north);
frame.getContentPane().add(BorderLayout.SOUTH, south);
frame.getContentPane().add(BorderLayout.CENTER, center);
frame.setSize(300,300);
frame.setVisible(true);
}
The center region gets whatever's leftl
(except in one special case we'll look at later)
8
u
f
fon o
b
j
e
c
f
I fhink I'm geffing if... if I'm in eust or
west, I gef my preferred widfh buf fhe
heighf is up fo fhe Ioyouf monoger. And
if I'm in north or south, if's jusf fhe
opposife-I gef my preferred heighf, buf
nof widfh.
5at vhat haeas
:a the :eate: :eg:aa!
c------l: - l- -.:l .-
--:l -l l-- ------ -l
c------l: - l- ---l .-
:--l -l l-- ------
-l
c------l: - l- :--l-- -l -.l--- :.:- : |-l ---, .:- -- l- -.-- ---:--: |?oo ?oo - l: :--`
?oo -|:
?
o
o
-
|
:
w-- ]-- -l :---l-
- l- ---l -- :--l, l
--: .|| l- -.] .:--::
l- -.--, :- l- l-:
- l- -.:l .- --:l
---'l - .: l.|| .: l-]
---| - l- ---l .- :--l ----: ---- --l]
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
408 chapter 13
fIow Iayout
FlowLayout cares
about the how of the
components:
left to right, top to bottom, in
the order they were added.
import javax.swing.*;
import java.awt.*;
public class Panel1 {
public static void main (String[] args) {
Panel1 gui = new Panel1();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
frame.getContentPane().add(BorderLayout.EAST, panel);
frame.setSize(200,200);
frame.setVisible(true);
}
}
Let's add a panel to the east region:
1- .--| --:-'l .- .-]l-
- l, :- l --:-'l .: -- --:
-l - l- -.:l ----
A JPoneI's Ioyouf monoger is FIowLoyouf, by defouIf. When we odd
o poneI fo o frome, fhe si;e ond pIocemenf of fhe poneI is sfiII
under fhe 8orderLoyouf monoger's confroI. 8uf onyfhing inside fhe
poneI (in ofher words, componenfs odded fo fhe poneI by coIIing
panel.add(aComponent)) ore under fhe poneI's FIowLoyouf
monoger's confroI. We'II sforf by puffing on empfy poneI in fhe frome's
eosf region, ond on fhe nexf poges we'II odd fhings fo fhe poneI.
M.- l- .--| -.] :- -- :.- :--
---- l : -- l- -.--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 409
public void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(shock me);
panel.add(button);
frame.getContentPane().add(BorderLayout.EAST, panel);
frame.setSize(250,200);
frame.setVisible(true);
}
Let's add a button to the panel
A l- -ll-- l- l- .--| .- . l-
.--| l- l- -.-- 1- .--|': |.]--l -.-.--
||--` :--l--|: l- -ll--, .- l- -.--':
|.]--l -.-.-- |----` :--l--|: l- .--|
1- .--| -.--'
A- l- -ll-- -l l:
------ :-- - -l
---:--:, -:.-:- l- .--|
-:-: |-- |.]--l, .- l-
-ll-- : .-l - l- .--|
|--l l- -.--`
P
o
n
e
I ob
j
e
c
f
I hove o buffon now,
so my Ioyouf monoger's
gonno hove fo fgure ouf
how big I need fo be...
8
u
f
fon o
b
j
e
c
f
The frome's
orderLuyout monoger
8osed on my fonf si;e
ond fhe number of
chorocfers, I wonf fo be 70
pixeIs wide ond Z0 pixeIs foII.
Ok... I need fo
know how big fhe
puneI wonfs fo be...
The poneI's
FIowLuyout monoger
I need
fo know how big fhe
button wonfs fo
confroIs confroIs
.
-
-
|
.--|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
410 chapter 13
public void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(shock me);
JButton buttonTwo = new JButton(bliss);
panel.add(button);
panel.add(buttonTwo);
frame.getContentPane().add(BorderLayout.EAST, panel);
frame.setSize(250,200);
frame.setVisible(true);
}
What happens if we add TWO buttons
to the panel?
-
.- 1
w
6
-ll--:
. B61+ l- l- .--|
what we wanted: what we got:
w
- -.-l l- -ll--:
:l.:- -- l- - -.:
-l--
1- .--| -.-- l- l -l -ll--: :- ] :-
--l:- l.l l- '|::' -ll-- : :-.||-- l.-
l- ':-: --' -ll-- l.l': -- |--
|.]--l ---: 1
- -ll-- -l: -:l -.l l
---: |.- -- ----`
+,-+ :+ ,-+:.|
JButton button = new JButton(shock me);
JButton buttonTwo = new JButton(bliss);
JButton buttonThree = new JButton(huh?);
panel.add(button);
panel.add(buttonTwo);
panel.add(buttonThree);
|f the code above were modied to the code below,
what would the GU| look likeI
Draw what you
think the GU| would
look like if you ran
the code to the left.
(Then try it!)
fIow Iayout
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 411
BoxLayout to the rescuel
t keeps components
stacked, even if there's room
to put them side by side.
Unlike FlowLayout, BoxLayout can force a
new line' to make the components wrap to
the next line, even if there's room for them
to ht horizontally.
8uf now you'II hove fo chonge fhe poneI's Ioyouf monoger from fhe
defouIf FIowLoyouf fo 8oxLoyouf.
public void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JButton button = new JButton(shock me);
JButton buttonTwo = new JButton(bliss);
panel.add(button);
panel.add(buttonTwo);
frame.getContentPane().add(BorderLayout.EAST, panel);
frame.setSize(250,200);
frame.setVisible(true);
}
c.-- l- |.]--l -.-.-- l- - . ---
-:l.-:- - B-|.]--l
1- B-|.]--l :--:l--:l-- ---: l- ---
l- :------l l: |.]- --l |-, l- .--|`
.- -: .: l- -:- |-- -:- /_Ax| -- .
--l:.| :l.:`
N-l:- -- l- .--| : -.------ ..-,
-:.-:- l --:-'l --- l- l -l -ll--:
-----l.||] - l- .--| l-| l- -.--
l ---- ---- ---- -- --|] l- |.--:l
-ll--, ':-: --'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
412 chapter 13
Iayout managers
(-,- a,- |
oa|| qa--(:|-
How come you can't add directIy to a frame the way
you can to a paneI!
A 1Prame is special because it's where the rubber
meets the road in making something appear on the screen.
while all your Swing components are pure 1ava, a 1Prame
has to connect to the underlying OS in order to access the
display. Think of the content pane as a l00% pure 1ava layer
that sits on to of the 1Prame. Or think of it as though 1Prame
is the window frame and the content pane is the... glass. ou
know, the window one. And you can even swo the content
pane with your own 1Panel, to make your 1Panel the frame's
content pane, using,
myFrame.setContentPane(myPanel);
Can I change the Iayout manager of the frame!
What if I want the frame to use ow instead of border!
The easiest way to do this is to make a panel, build
the GU| the way you want in the panel, and then make that
panel the frame's content pane using the code in the previ-
ous answer (rather than using the default content pane).
What if I want a different preferred size! Is there a
setSize() method for components!
es, there is a setSize(), but the layout managers will
ignore it. There's a distinction between the teletteJ s|ze of
the component and the size you want it to be. The preferred
size is based on the size the component actually neeJs
(the component makes that decision for itself ). The layout
manager calls the component's getPreferredSize() method,
and thot method doesn't cote if you've previously called
setSize() on the component.
Can't I just put things where I want them! Can I turn
the Iayout managers off!
ep. On a component by component basis, you can call
setLayout(null) and then it's up to you to hard-code
the exact screen locations and dimensions. |n the long run,
though, it's almost always easier to use layout managers.
8ll P0lk5
Layoul raraers corlro| l|e s|ze ard |ocal|or ol
corporerls resled W|l||r ol|er corporerls.
w|er you add a corporerl lo arol|er corporerl
(sorel|res relerred lo as a oaokgrouno corporerl,
oul l|al's rol a lec|r|ca| d|sl|rcl|or), l|e added
corporerl |s corlro||ed oy l|e |ayoul raraer ol l|e
oaokgrouno corporerl.
A |ayoul raraer as|s corporerls lor l|e|r
prelerred s|ze, oelore ra||r a dec|s|or aooul
l|e |ayoul. 0eperd|r or l|e |ayoul raraer's
po||c|es, |l r||l respecl a||, sore, or rore ol l|e
corporerl's W|s|es.
T|e 8orderLayoul raraer |els you add a
corporerl lo ore ol l|ve re|ors. You rusl spec|ly
l|e re|or W|er you add l|e corporerl, us|r l|e
lo||oW|r syrlax:
add(BorderLayout.EAST, panel);
w|l| 8orderLayoul, corporerls |r l|e rorl| ard
soul| el l|e|r prelerred |e||l, oul rol W|dl|.
Corporerls |r l|e easl ard Wesl el l|e|r prelerred
W|dl|, oul rol |e||l. T|e corporerl |r l|e cerler
els W|alever |s |ell over (ur|ess you use pack()).
T|e pac|() rel|od |s |||e s|r|r|-Wrap lor l|e
corporerls, |l uses l|e lu|| prelerred s|ze ol l|e
cerler corporerl, l|er delerr|res l|e s|ze ol l|e
lrare us|r l|e cerler as a slarl|r po|rl, ou||d|r
l|e resl oased or W|al's |r l|e ol|er re|ors.
F|oWLayoul p|aces corporerls |ell lo r||l, lop lo
oollor, |r l|e order l|ey Were added, Wrapp|r lo a
reW ||re ol corporerls or|y W|er l|e corporerls
Wor'l l|l |or|zorla||y.
F|oWLayoul |ves corporerls l|e|r prelerred s|ze |r
ool| d|rers|ors.
8oxLayoul |els you a||r corporerls slac|ed
verl|ca||y, ever |l l|ey cou|d l|l s|de-oy-s|de. L||e
F|oWLayoul, 8oxLayoul uses l|e prelerred s|ze ol
l|e corporerl |r ool| d|rers|ors.
8orderLayoul |s l|e delau|l |ayoul raraer lor a
lrare, F|oWLayoul |s l|e delau|l lor a pare|.
ll you Warl a pare| lo use sorel||r ol|er l|ar l|oW,
you |ave lo ca|| setLayout() or l|e pare|.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
using swing
you are here 413
||zy|n] w| !h 8w|n] rempencn!s
You`vc lcaincu ihc lasics ol layoui managcis, so now lci`s iiy oui a
lcw ol ihc mosi common comoncnis: a icxi hclu, sciolling icxi aica,
chccIlox, anu lisi. Wc won`i show you ihc wholc uain API loi cach ol
ihcsc, |usi a lcw highlighis io gci you siaiicu.
JTextField
Constructors
JTextField eld = new JTextField(20);
How to use it
0ef fexf ouf of if
System.out.println(eld.getText());
1
Puf fexf in if
eld.setText(whatever);
eld.setText();
2
0ef on AcfionEvenf when fhe user
presses refurn or enfer
eld.addActionListener(myActionListener);
3
/-- :.- .|:- --:l-- -- -] ---l: ]--
--.||] -.-l l- -.- .--l l ---] l-- l-
-:-- --::-: . -]
io --.-: io :-|---:, --l io -|:
1: ---: l- ------ -l -
l- l-l -|
JTextField eld = new JTextField(Your name);
SeIecf/HighIighf fhe fexf in fhe feId
eld.selectAll();
4
Puf fhe cursor bock in fhe feId (so fhe user
con jusf sforf fyping)
eld.requestFocus();
5
)1-l|-|
)
|
.
-
|
1: :|-.-: l- -|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
414 chapter 13
JTextArea
Constructor
JTextArea text = new JTextArea(10,20);
How to use it
Moke if hove o verficoI scroIIbor onIy
JScrollPane scroller = new JScrollPane(text);
text.setLineWrap(true);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
1
PepIoce fhe fexf fhof's in if
text.setText(Not all who are lost are wandering);
2
M
.- . ):--|||.-- .- - l l-
l-l .--. l.l l': -- l- ::--|| --
|o --.-: |o |--: |:-l: l- ------ -l`
SeIecf/HighIighf fhe fexf in fhe feId
text.selectAll();
4
Puf fhe cursor bock in fhe feId (so fhe user
con jusf sforf fyping)
text.requestFocus();
5
io --.-: io :-|---: |:-l: l- ------ -l`
UnIike JTexfFieId, JTexfAreo con hove more fhon one Iine of fexf. If
fokes o IiffIe confgurofion fo moke one, becouse if doesn'f come ouf of
fhe box wifh scroII bors or Iine wropping. To moke o JTexfAreo scroII, you
hove fo sfick if in o ScroIIPone. A ScroIIPone is on objecf fhof reoIIy Ioves
fo scroII, ond wiII foke core of fhe fexf oreo's scroIIing needs.
Append fo fhe fexf fhof's in if
text.append(button clicked);
3
1--- -- |-- --.-
1-|| l- ::--|| .-- l- -:- --|]
. --l:.| ::--||.-
|---l.-l'' /-- - l- l-l .--. l- l- ::--|| .-- |l--- l-
::--|| .-- :--:l--:l--`, l-- . l- ::--|| .-- l- l- .--| /--
--'l . l- l-l .--. --:l|] l- l- .--|'
text area
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 415
JTextArea example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TextArea1 implements ActionListener {
JTextArea text;
public static void main (String[] args) {
TextArea1 gui = new TextArea1();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton(Just Click It);
button.addActionListener(this);
text = new JTextArea(10,20);
text.setLineWrap(true);
JScrollPane scroller = new JScrollPane(text);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.getContentPane().add(BorderLayout.SOUTH, button);
frame.setSize(350,300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ev) {
text.append(button clicked \n );
}
}
|-:--l . --- |-- :- l- ---: - -- . :-.-.l- |-- -.: l-- l- -ll-- : :|:- 6l---:-, l-]'|| --- l--l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
416 chapter 13
JCheckBox
Constructor
JCheckBox check = new JCheckBox(Goes to 11);
How to use it
Lisfen for on ifem evenf (when if's seIecfed or deseIecfed)
check.addItemListener(this);
1
HondIe fhe evenf (ond fnd ouf whefher or nof if's seIecfed)
public void itemStateChanged(ItemEvent ev) {
String onOrOff = off;
if (check.isSelected()) onOrOff = on;
System.out.println(Check box is + onOrOff);
}
2
SeIecf or deseIecf if in code
check.setSelected(true);
check.setSelected(false);
3
check box
(-,- a,- |
oa|| qa--(:|-
Aren't the Iayout manag-
ers just more troubIe than they're
worth! If I have to go to aII this
troubIe, I might as weII just hard-
code the size and coordinates for
where everything shouId go.
Getting the exact layout
you want from a layout man-
ager can be a challenge. 8ut think
about what the layout manager
is really doing for you. Lven the
seemingly simple task of figuring
out where things should go on
the screen can be complex. Por
example, the layout manager takes
care of keeping your components
from overlapping one another.
|n other words, it knows how to
manage the spacing between
components (and between the
edge of the frame). Sure you can
do that yourself, but what happens
if you want components to be
very tightly packedI ou might get
them placed |ust right, by hand,
but that's only good for your 1vM!
whyI 8ecause the components
can be slightly different from
platform to platform, especially if
they use the underlying platform's
native 'look and feel'. Subtle things
like the bevel of the buttons can
be different in such a way that
components that line up neatly
on one platform suddenly squish
together on another.
And we're still not at the really 8ig
Thing that layout managers do.
Think about what happens when
the user resizes the window! Or
your GU| is dynamic, where com-
ponents come and go. |f you had
to keep track of re-laying out all
the components every time there's
a change in the size or contents of
a background component...yikes!
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 417
JList
Constructor
String [] listEntries = {alpha, beta, gamma, delta,
epsilon, zeta, eta, theta };
list = new JList(listEntries);
How to use it
Moke if hove o verficoI scroIIbor
JScrollPane scroller = new JScrollPane(list);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
1
Pesfricf fhe user fo seIecfing onIy OME fhing of o fime
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
3
Pegisfer for Iisf seIecfion evenfs
list.addListSelectionListener(this);
4
HondIe evenfs (fnd ouf which fhing in fhe Iisf wos seIecfed)
public void valueChanged(ListSelectionEvent lse) {
if( !lse.getValueIsAdjusting()) {
String selection = (String) list.getSelectedValue();
System.out.println(selection);
}
}
5
Sef fhe number of Iines fo show before scroIIing
list.setVisibleRowCount(4);
2
1: : -:l |- -l )1-lA--. ~~ ]-- -.- .
):--|||.-- |.- - l l- |:l`, l-- . l-
::--|| .-- |N61 l- |:l` l- l- .--|
/--'|| -l l- ---l 1w|c! ]-- --'l
-l - l: l-:l
-l-|-:l-/.|--|` .:l-.||]
--l---: .- 6-:l A |:l :-'l
|-l- l- --|] l-- --:l:
)|:l :--:l--:l-- l.-: .- .--.] - .-] --:l
l]- 1-] --'l .- l- - l--:, -l .
l-- ----:--l.l-- -|| .-.- - l- |:l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
418 chapter 13
CaJe kit:hea
This a:t's atiaaa|. he':e a|iag the Ia|| 5eat5ax, 6l!
aaJ a||. !a the Saviag 0le:ts :hate:, ve'|| |ea:a hav ta
save aaJ :esta:e J:a atte:as. Iiaa||y, ia the aetva:|iag
:hate: lKa|e a Caaae:tiaaI, ve'|| ta:a the 5eat5ax iata a
va:|iag :hat :|ieat.
Code Kitchen
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 419
This is ihc lull couc lisiing loi ihis vcision ol ihc BcaiBox, wiih luiions loi siaiiing,
sioing, anu changing ihc icmo. Thc couc lisiing is comlcic, anu lully-
annoiaicu, lui hcic`s ihc ovcivicw:
Mzk|n] !hc Bcz!Ber
1
2
3
4
8uiId o 0UI fhof hos Zbo checkboxes (JCheck8ox) fhof sforf ouf
unchecked, Io IobeIs (JLobeI) for fhe insfrumenf nomes, ond four
buffons.
Pegisfer on AcfionLisfener for eoch of fhe four buffons. We don'f
need Iisfeners for fhe individuoI checkboxes, becouse we oren'f
frying fo chonge fhe poffern sound dynomicoIIy (i.e. os soon os fhe
user checks o box). Insfeod, we woif unfiI fhe user hifs fhe 'sforf'
buffon, ond fhen woIk fhrough oII Zbo checkboxes fo gef fheir sfofe
ond moke o MIDI frock.
Sef-up fhe MIDI sysfem (you've done fhis before) incIuding geffing
o Sequencer, moking o Sequence, ond creofing o frock. We ore using
o sequencer mefhod fhof's new fo Jovo b.0, sefLoopCounf( ). This
mefhod oIIows you fo specify how mony fimes you wonf o sequence
fo Ioop. We're oIso using fhe sequence's fempo focfor fo odjusf fhe
fempo up or down, ond moinfoin fhe new fempo from one iferofion of
fhe Ioop fo fhe nexf.
When fhe user hifs 'sforf', fhe reoI ocfion begins. The evenf-hondIing
mefhod for fhe 'sforf' buffon coIIs fhe buiIdTrockAndSforf() mefhod.
In fhof mefhod, we woIk fhrough oII Zbo checkboxes (one row of
o fime, o singIe insfrumenf ocross oII Io beofs) fo gef fheir sfofe,
fhen use fhe informofion fo buiId o MIDI frock (using fhe hondy
mokeEvenf() mefhod we used in fhe previous chopfer). Once fhe frock
is buiIf, we sforf fhe sequencer, which keeps pIoying (becouse we're
Iooping if) unfiI fhe user hifs 'sfop'.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
420 chapter 13
import java.awt.*;
import javax.swing.*;
import javax.sound.midi.*;
import java.util.*;
import java.awt.event.*;
public class BeatBox {
JPanel mainPanel;
ArrayList<JCheckBox> checkboxList;
Sequencer sequencer;
Sequence sequence;
Track track;
JFrame theFrame;
String[] instrumentNames = {Bass Drum, Closed Hi-Hat,
Open Hi-Hat,Acoustic Snare, Crash Cymbal, Hand Clap,
High Tom, Hi Bongo, Maracas, Whistle, Low Conga,
Cowbell, Vibraslap, Low-mid Tom, High Agogo,
Open Hi Conga};
int[] instruments = {35,42,46,38,49,39,50,60,70,72,64,56,58,47,67,63};
public static void main (String[] args) {
new BeatBox2().buildGUI();
}
public void buildGUI() {
theFrame = new JFrame(Cyber BeatBox);
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout layout = new BorderLayout();
JPanel background = new JPanel(layout);
background.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
checkboxList = new ArrayList<JCheckBox>();
Box buttonBox = new Box(BoxLayout.Y_AXIS);
JButton start = new JButton(Start);
start.addActionListener(new MyStartListener());
buttonBox.add(start);
JButton stop = new JButton(Stop);
stop.addActionListener(new MyStopListener());
buttonBox.add(stop);
JButton upTempo = new JButton(Tempo Up);
upTempo.addActionListener(new MyUpTempoListener());
buttonBox.add(upTempo);
JButton downTempo = new JButton(Tempo Down);
BeatBox code
w- :l--- l- :-:--: - .- A--.]|:l
1-:- .-- l- -.--: - l- -:l-----l:, .: . l--
.--.], -- -|- l- 6c| |.-|: |-- -.: ---`
1-:- ----:--l l- .:l-.| --- '-]:'
1- --- :.---| : |- . .--, -:-l
-.: '-]' -- l- .-- : . ----l ---
- l- ----- '?-' : l- -] -- l- B.::
---, +i : c|-:- +~+.l, -l:
N-l- :-:.| ---, -:l |-l: - 6c|
:-- /--'- :--- --:l - l ----
A- '--l] ----' -: -: . -.-- -l---- l- --: - l- .--| .- ---- l- :------l: .-- |.:-
|---|] .-:l-l:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 421
downTempo.addActionListener(new MyDownTempoListener());
buttonBox.add(downTempo);
Box nameBox = new Box(BoxLayout.Y_AXIS);
for (int i = 0; i < 16; i++) {
nameBox.add(new Label(instrumentNames[i]));
}
background.add(BorderLayout.EAST, buttonBox);
background.add(BorderLayout.WEST, nameBox);
theFrame.getContentPane().add(background);
GridLayout grid = new GridLayout(16,16);
grid.setVgap(1);
grid.setHgap(2);
mainPanel = new JPanel(grid);
background.add(BorderLayout.CENTER, mainPanel);
for (int i = 0; i < 256; i++) {
JCheckBox c = new JCheckBox();
c.setSelected(false);
checkboxList.add(c);
mainPanel.add(c);
} // end loop
setUpMidi();
theFrame.setBounds(50,50,300,300);
theFrame.pack();
theFrame.setVisible(true);
} // close method
public void setUpMidi() {
try {
sequencer = MidiSystem.getSequencer();
sequencer.open();
sequence = new Sequence(Sequence.PPQ,4);
track = sequence.createTrack();
sequencer.setTempoInBPM(120);
} catch(Exception e) {e.printStackTrace();}
} // close method
l|| ---- 6c| :-l~- :--
N-l- ---.-.|-
M.- l- :-:--:, :-l l-- l-
'.|:-' |:- l-] .---'l :-:-` .-
. l-- l- l- A--.]|:l ANl l-
l- 6c| .--|
1- -:-.| M|l| :-l~- :l- --
-ll- l- ----:--, l- ----:-,
.- l- 1-.: A.-, --l- :-:.|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
422 chapter 13
public void buildTrackAndStart() {
int[] trackList = null;
sequence.deleteTrack(track);
track = sequence.createTrack();
for (int i = 0; i < 16; i++) {
trackList = new int[16];
int key = instruments[i];
for (int j = 0; j < 16; j++ ) {
JCheckBox jc = (JCheckBox) checkboxList.get(j + (16*i));
if ( jc.isSelected()) {
trackList[j] = key;
} else {
trackList[j] = 0;
}
} // close inner loop
makeTracks(trackList);
track.add(makeEvent(176,1,127,0,16));
} // close outer
track.add(makeEvent(192,9,1,0,15));
try {
sequencer.setSequence(sequence);
sequencer.setLoopCount(sequencer.LOOP_CONTINUOUSLY);
sequencer.start();
sequencer.setTempoInBPM(120);
} catch(Exception e) {e.printStackTrace();}
} // close buildTrackAndStart method
public class MyStartListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
buildTrackAndStart();
}
} // close inner class
w-'|| -.- . ||~-|----l .--.] l- -| l- .|--: --
--- -:l-----l, .:--:: .|| || -.l: | l- -:l-----l :
:--:- l- |.] -- l.l -.l, l- .|-- .l l.l -|----l
-|| - l- -] | l.l -:l-----l : N61 :--:- l-
|.] -- l.l -.l, -l - . ----
|: l- :-:- .l l: -.l :-|-:l- | ]-:, -l
l- -] .|-- - l: :|-l - l- .--.] |l- :|-l l.l
----:--l: l: -.l` 6l---:-, l- -:l-----l :
N61 :--:- l- |.] .l l: -.l, :- :-l l l- ----
- l: -- -.: - l- || 6w |- B.::, c---, -l:`
-l l- '-]' l.l ----:--l: -: -:l-----l l:
: |B.::, +~+.l, -l: 1- -:l-----l: .--.] -|: l-
.:l-.| M|l| -----: -- -.: -:l-----l`
N6w ||A/ 1+! 1+|N6''
|-:l - l- ---- :|.::-:,
|:l----: -- l- -ll--:
N-l- :-:.| ---
1: : ---- l .|| .--:' w--- --
l--- :-:- :l.l- -l- M|l| ---l:,
.- . l-- l- l- 1-.:
BeatBox code
l- l: -- -.: - l- B!A1 -- l: ---
|-- l: -:l-----l, .- -- .|| || -.l:,
-.- ---l: .- . l-- l- l- l-.:
w- .|-.]: -.-l l- -.- :--- l.l l--- | .- ---l .l
-.l || |l --: o l- |-` 6l---:-, l- B-.lB- -l
--l - l- -|| || -.l: ---- l :l.-l: ---
-l - - l- -| l-.:, -.- . --: ---
|-l': ]-- :-:] l- -----
- |-- l--.l--:, -- - l:
:.:-, :--l----: |---
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
using swing
you are here 423
public class MyStopListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
sequencer.stop();
}
} // close inner class
public class MyUpTempoListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
oat tempoFactor = sequencer.getTempoFactor();
sequencer.setTempoFactor((oat)(tempoFactor * 1.03));
}
} // close inner class
public class MyDownTempoListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
oat tempoFactor = sequencer.getTempoFactor();
sequencer.setTempoFactor((oat)(tempoFactor * .97));
}
} // close inner class
public void makeTracks(int[] list) {
for (int i = 0; i < 16; i++) {
int key = list[i];
if (key != 0) {
track.add(makeEvent(144,9,key, 100, i));
track.add(makeEvent(128,9,key, 100, i+1));
}
}
}
public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) {
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);
} catch(Exception e) {e.printStackTrace(); }
return event;
}
} // close class
1- -l-- ---- :|.::
|:l----: -- l- -ll--:
M.- l- N61! 6N .-
N61 6|| ---l:, .-
. l-- l- l- 1-.:
1: : l- -l|l] --l- --- |.:l
:.l--': c--rl:-- N-l- ---
1: -.-: ---l: -- --- -:l-----l .l . l--, --
.|| || -.l: - l -l -l .- -l| 1 -- l- B.::
---, .- -.: -- - l- .--.] -|| -| -l--
l- -] - l.l -:l-----l, -- . ---- | l': . ----,
l- -:l-----l :-'l :--:- l- |.] .l l.l -.l
6l---:-, -.- .- ---l .- . l l- l- l-.:
1- 1--- |.:l-- ::.|-:
l- :----:--': l--- ]
l- .:l-- --- 1-
-.-|l : |o, :- --'--
.-:l- +/~ ?* --
:|:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
424 chapter 13
y[je[ e] g, wj([
w[je[ ]zya(/
Five of the six screens below were made from one
of the code fragments on the opposite page. Match
each of the fve code fragments with the layout that
fragment would produce.
exercise: Which Layout?
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 425
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(tesuji);
JButton buttonTwo = new JButton(watari);
frame.getContentPane().add(BorderLayout.NORTH,panel);
panel.add(buttonTwo);
frame.getContentPane().add(BorderLayout.CENTER,button);
(] Jzgn(,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
426 chapter 13
(([(iss ).c
ou can do it.
2. Swing's dad
3. Prame's purview
5. Help's home
6. More fun than text
7. Component slang
8. Pomulin command
9. Arrange
l0. 8order's top
l. Artist's sandbox
4. 8order's catchall
5. 1ava look
9. Generic waiter
ll. A happening
l2. Apply a widget
l5. 1Panel's default
l6. Polymorphic test
l7. Shake it baby
2l. Lots to say
23. Choose many
25. 8utton's pal
26. Home of
actionPerformed
l3. Manager's rules
l4. Source's behavior
l5. 8order by default
l8. User's behavior
l9. |nner's squeeze
20. 8ackstage widget
22. Mac look
24. 8order's right
l 2
l5
l7
24
l8 l9
l0
25
5
ll
4
9
22
26
l6
l2
2l
23
8
3
6
l4
l3
7
20
puzzIe: crossword
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
using swing
you are here 427
1
B
4
B
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(tesuji);
JButton buttonTwo = new JButton(watari);
panel.add(buttonTwo);
frame.getContentPane().add(BorderLayout.CENTER,button);
frame.getContentPane().add(BorderLayout.EAST, panel);
B
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(tesuji);
JButton buttonTwo = new JButton(watari);
panel.add(buttonTwo);
frame.getContentPane().add(BorderLayout.CENTER,button);
0
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(tesuji);
JButton buttonTwo = new JButton(watari);
panel.add(button);
frame.getContentPane().add(BorderLayout.NORTH,buttonTwo);
frame.getContentPane().add(BorderLayout.EAST, panel);
A
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(tesuji);
JButton buttonTwo = new JButton(watari);
frame.getContentPane().add(BorderLayout.SOUTH,panel);
panel.add(buttonTwo);
frame.getContentPane().add(BorderLayout.NORTH,button);
B
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
JButton button = new JButton(tesuji);
JButton buttonTwo = new JButton(watari);
frame.getContentPane().add(BorderLayout.NORTH,panel);
panel.add(buttonTwo);
frame.getContentPane().add(BorderLayout.CENTER,button);
D
[yej, ]a(jn,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
428 chapter 13
(([(iss ).c
l 2
l5
l7
24
l8 l9
l0
25
5
ll
4
9
22
26
l6
l2
2l
23
8
3
6
l4
l3
7
20
]arr[c nsacis
D P A W P A M E L S
W C E M T E P
M E T A L T 0 W
S E L I S T E M E P I
E V E M T A I O A D D
T U P Y Z P P 0
V C F L O W O E T H E
I S A P L U H I T
S L A M I M A T I O M C
I L M C C U P
8 8 E Y T E X T A P E A A
L A I E Q M
E C H E C I 8 O X P U E
I A M L A 8 E L
S
A C T I O M L I S T E M E P
puzzIe answers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
this is a new chapter 429
14 seriaIization and fiIe I/O
Objects can be fIattened and infIated. Ob|ects have state and behavior.
8ehov|ot lives in the closs, but stote lives within each individual ooject. So what happens when
it's time to sove the state of an ob|ectI |f you're writing a game, you're gonna need a Save/
Pestore Game feature. |f you're writing an app that creates charts, you're gonna need a Save/
Open Pile feature. |f your program needs to save state, you con Jo |t the hotJ woy, interrogating
each ob|ect, then painstakingly writing the value of each instance variable to a file, in a
format you create. Or, you can do it the easy DD wayyou simply freeze-dry/flatten/persist/
dehydrate the ob|ect itself, and reconstitute/inflate/restore/rehydrate it to get it back. 8ut you'll
still have to do it the hard way somet|mes, especially when the file your app saves has to be read
by some other non-1ava application, so we'll look at both in this chapter.
If I hove fo reod
one more fIe fuII of
dofo, I fhink I'II hove fo kiII him. He
knows I con sove whoIe objecfs, buf
does he Ief me7 , fhof wouId be
foo eosy. WeII, we'II jusf see how
he feeIs offer I...
8aving Ob]ects
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
430 chapter 14
You`vc nJe ihc cilcci aiicin. You wani io n.e ihc aiicin.
You coulu gial a iccc ol aci anu siaii sciillling ii uown, lui
insicau you hii ihc luiion oi choosc Savc liom ihc Iilc
mcnu). Thcn you givc ii a namc, icI a uiiccioiy,
anu cxhalc Inowing ihai youi masiciiccc won`i go
oui ihc winuow wiih ihc lluc sciccn ol ucaih.
You havc lois ol oiions loi how io savc ihc siaic ol
youi ]ava iogiam, anu whai you choosc will iolally
uccnu on how you lan io ue ihc savcu siaic. Hcic
aic ihc oiions wc`ll lc looIing ai in ihis chaici.
saving objects
0zp!erc !hc Bcz!
Use seriuIizution
Wrife o fIe fhof hoIds offened (serioIi;ed)
objecfs. Then hove your progrom reod fhe
serioIi;ed objecfs from fhe fIe ond inofe fhem
bock info Iiving, breofhing, heop-inhobifing objecfs.
1
f your data will be used by only the Java
program that generated it:
Thcsc aicn`i ihc only oiions, ol couisc. You can savc uaia in any
loimai you choosc. Insicau ol wiiiing chaiacicis, loi cxamlc,
you can wiiic youi uaia as lyics. Oi you can wiiic oui any Iinu
ol ]ava iimiiivc n a ]ava iimiiivc-ihcic aic mcihous io wiiic
inis, longs, loolcans, cic. Bui icgaiulcss ol ihc mcihou you usc,
ihc lunuamcnial I/O icchniqucs aic iciiy much ihc samc:
wiiic somc uaia io oeL.r, anu usually ihai somcihing is ciihci
a hlc on uisI oi a siicam coming liom a nciwoiI conncciion.
Rcauing ihc uaia is ihc samc ioccss in icvcisc: icau somc uaia
liom ciihci a hlc on uisI oi a nciwoiI conncciion. Anu ol couisc
cvciyihing wc ialI aloui in ihis aii is loi iimcs whcn you aicn`i
using an aciual uaialasc.
f your data will be used by other programs:
Write u pIuin tet h Ie
Wrife o fIe, wifh deIimifers fhof ofher progroms con porse.
For exompIe, o fob-deIimifed fIe fhof o spreodsheef or
dofobose oppIicofion con use.
2
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 431
Opfion fwo
Write u pIuin tet h Ie
Creofe o fIe ond wrife fhree Iines of fexf,
one per chorocfer, seporofing fhe pieces
of sfofe wifh commos:
S0,BIt,bcw, swcrd,dust
B00,TrcII,bare hands,bIg ax
1B0,magIcIan,speIIs,InvIsIbIIIty
2
1- :--.|-- |- : --: .--- -- --.-: l- --.,
-l l': --: -.:-- |.- :.--` -- ]--- ---.- l-
--:l--- l- l--- --:l: --- :--.|-.l-- l.- ---
--.- - l- --:l': .-.|- .|--: l.l ---- :.-
l- . l-l |- |-- -.-|-, -.-- .|| l- -.]: - -:
]-- :--| .::--l.||] --. .: l- .|--: - l- ----
----' 1- l]- -l -:--- -:l' -:l-. - !|',
-|- l- !| -:---: . --.--
!
ag:ae yaa
h
ave th
:ee ga
e
:h
a:a:te:s ta save...
8zv|n] 8!z!c
Imaginc you havc a iogiam, say, a laniasy
auvcniuic gamc, ihai iaIcs moic ihan onc
scssion io comlcic. As ihc gamc iogicsscs,
chaiacicis in ihc gamc lccomc siiongci, wcaIci,
smaiici, cic., anu gaihci anu usc anu losc)
wcaons. You uon`i wani io siaii liom sciaich
cach iimc you launch ihc gamc-ii iooI you
loicvci io gci youi chaiacicis in io shac loi
a scciaculai laiilc. So, you nccu a way io savc
ihc siaic ol ihc chaiacicis, anu a way io icsioic
ihc siaic whcn you icsumc ihc gamc. Anu sincc
you`ic also ihc gamc iogiammci, you wani ihc
wholc savc anu icsioic ihing io lc as casy anu
looliool) as ossillc.
Came6haracter
|rl poWer
3lr|r lype
weapor[| Weapors
elweapor()
useweapor()
|rcreasePoWer()
// rore
o
bjec
f
---- -o
l]- !|
--.--: --,
:---, -:l
Opfion one
Write the three seriuIized
churucter objects to u h Ie
Creofe o fIe ond wrife fhree serioIi;ed
chorocfer objecfs. The fIe won'f moke
sense if you fry fo reod if os fexf:
1sr0ame0haracter
%gSmU1pcwerLjavaIang
StrIngweapcnstLjavaIang
StrIngxpBtIturLjava.Iang.StrIng="VA
B(0xptbcwtswcrdtdustsgtTrcIIugtb
are handstbIg axsgxtmagIcIanugtspe
IIstInvIsIbIIIty
1
---- ioo
l]- 1--||
--.--: .--
.-:, .
---- |io
l]- M.:.-
--.--: :-||:,
-:|l]
o
bjec
f
o
bjec
f
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
saving objects
432 chapter 14
Hcic aic ihc sics loi sciializing saving) an ol|cci. Don`i loihci
mcmoiizing all ihis, wc`ll go inio moic uciail laici in ihis chaici.
Wr| !|n] z scr|z||zc4 e|jcr! !e z f||c
FileOutputStream leStream = new FileOutputStream(MyGame.ser);
M
.- . ||-6-l-ll--.- --:l ||-6-l-ll--.-
---: -- l- :----:l l- |.- :--.l-` . |-
Muke u FiIeOutputStreum
os.writeObject(characterOne);
os.writeObject(characterTwo);
os.writeObject(characterThree);
Muke un ObjectOutputStreum
6-:l6-l-ll--.- |-l: ]-- --l- --:l:,
-l l :.-'l --:l|] :----:l l- . |- |l
---: l- - - . '-|--' 1: : .:l-.||]
:.||- ':.--' --- :l--.- l- .--l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
seriaIization and fiIe I/O
you are here 433
Thc ]ava I/O API has connection siicams, ihai icicscni conncciions io ucsiinaiions anu
souiccs such as hlcs oi nciwoiI socIcis, anu choin siicams ihai woiI only il chaincu io
oihci siicams.
Olicn, ii iaIcs ai lcasi iwo siicams hooIcu iogcihci io uo somcihing usclul-ore io
icicscni ihc conncciion anu nroLe. io call mcihous on. Why iwo. Bccausc orre.or
siicams aic usually ioo low-lcvcl. IilcOuiuiSiicam a conncciion siicam), loi cxamlc,
has mcihous loi wiiiing b,e. Bui wc uon`i wani io wiiic b,e! Wc wani io wiiic obe, so
wc nccu a highci-lcvcl Ln.r siicam.
OK, ihcn why noi havc |usi a singlc siicam ihai uocs e:nI, whai you wani. Onc ihai lcis
you wiiic ol|ccis lui unucincaih convciis ihcm io lyics. ThinI goou OO. Each class
uocs ore ihing wcll. IilcOuiuiSiicams wiiic lyics io a hlc. Ol|cciOuiuiSiicams iuin
ol|ccis inio uaia ihai can lc wiiiicn io a siicam. So wc maIc a IilcOuiuiSiicam ihai lcis
us wiiic io a hlc, anu wc hooI an Ol|cciOuiuiSiicam a chain siicam) on ihc cnu ol ii.
Whcn wc call wiiicOl|cci) on ihc Ol|cciOuiuiSiicam, ihc ol|cci gcis umcu inio ihc
siicam anu ihcn movcs io ihc IilcOuiuiSiicam whcic ii uliimaicly gcis wiiiicn as lyics
io a hlc.
Thc aliliiy io mix anu maich uillcicni comlinaiions ol conncciion anu chain siicams
givcs you iicmcnuous ucxililiiy! Il you wcic loiccu io usc only a .rIe siicam class, you`u
lc ai ihc mcicy ol ihc API ucsigncis, hoing ihcy`u ihoughi ol e.e.,L.r you mighi cvci
wani io uo. Bui wiih chaining, you can aich iogcihci youi own uo chains.
Pz!z mevcs |n s!rczms frem enc p|zrc !e zne!hcr.
---.
D.::.-+:.--
Objecf
ObjecfOufpufSfreom
(o choin sfreom)
is wriffen fo
objecf is offened (serioIi;ed)
FiIeOufpufSfreom
(o connecfion sfreom)
0II0I00I0II0III00I
objecf is wriffen os byfes fo
0II0I00I
0II0III0
0I
FiIe
0enncr!|en
s!rczms rcprcscn!
z renncr!|en
!e z seerrc er
4cs!|nz!|en |f||c,
serkc!, c!r.I wh||c
rhz|n s!rczms
rzn! renncr! en
!hc|r ewn zn4 mes!
|c rhz|nc4 !e z
renncr!|en s!rczm.
is choined fo
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
434 chapter 14
Objecfs on fhe heop hove sfofe-fhe
voIue of fhe objecf's insfonce
voriobIes. These voIues moke one
insfonce of o cIoss differenf from
onofher insfonce of fhe some cIoss.
Whz! rcz||y hzppcns !e zn e|jcr!
whcn | !s scr|z||zc4!
Foo myFoo = new Foo();
myFoo.setWidth(37);
myFoo.setHeight(70);
FileOutputStream fs = new FileOutputStream(foo.ser);
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(myFoo);
Ob]ect on the heap Ob]ect serialized
seriaIized objects
0
0
I
0
0
I
0
I
widfh
0
I
0
0
0
I
I
0
heighf
00I00I0I
0I000II0
SerioIi;ed objecfs suve the vuIues
of the instunce vuriubIes, so fhof
on idenficoI insfonce (objecf) con be
broughf bock fo Iife on fhe heop.
1- -:l.-:- .-.|- .|--:
-- -l .- -l .--
:.- l- l- |- --:--',
.|-- -l . |ll|- ---- --
l- )/M ---: l- --:l---
l- --:l ||- -.l l:
:|.:: l]- :` foo.ser
6
-:l -
l l-
- --
l-
-:l.-:- .-.|-:
1- .|--: .-- :-:-
--l .- --- -l-
l- :l--.-
M.- . ||-6-l-ll--.- l.l :----:l:
l- l- |- --:--', l-- :.- .-
6-:l6-l-ll--.- l- l, .- l-|| l-
6-:l6-l-ll--.- l- --l- l- --:l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 435
Be! whz! crzr!|y |8 zn e|jcr!s s!z!c!
Whz! ncc4s !e |c szvc4!
Now ii siaiis io gci inicicsiing. Easy cnough io savc ihc .....e
valucs S7 anu 70. Bui whai il an ol|cci has an insiancc vaiiallc
ihai`s an ol|cci .ee.ere. Whai aloui an ol|cci ihai has hvc
insiancc vaiiallcs ihai aic ol|cci iclcicnccs. Whai il ihosc ol|cci
insiancc vaiiallcs ihcmsclvcs havc insiancc vaiiallcs.
ThinI aloui ii. Whai aii ol an ol|cci is oicniially uniquc.
Imaginc whai nccus io lc icsioicu in oiuci io gci an ol|cci ihai`s
iucniical io ihc onc ihai was savcu. Ii will havc a uillcicni mcmoiy
locaiion, ol couisc, lui wc uon`i caic aloui ihai. All wc caic aloui
is ihai oui ihcic on ihc hca, wc`ll gci an ol|cci ihai has ihc samc
siaic ihc ol|cci hau whcn ii was savcu.
Engine
Tire []
T
i
r
e
[
]
orro
y
o
b
j
e
c
f
E
n
g
i
n
e ob
j
e
c
f
C
o
r
obj
e
c
f
The Car ob]ect has two
instance variables that
reference two other
ob]ects.
8f8l 88f00ll
what has to happen for the Car
ob|ect to be saved in such a way
that it can be restored back to its
original stateI
Think of whatand howyou
might need to save the Car.
And what happens if an Lngine
ob|ect has a reference to a
CarburatorI And what's inside the
Tire || array ob|ectI
What does it take to
save a Car ob]ect?
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
436 chapter 14
When an ob]ect is serialized, all the ob]ects
it refers to from instance variables are also
serialized. And all the ob]ects those ob]ects
refer to are serialized. And all the ob]ects those
ob]ects refer to are serialized... and the best
part is, it happens automaticallyl
Dog
leel
Dog
|erl
C
o
I
I
o
r
ob
j
e
c
f
S
f
r
i
n
g o
b
j
e
c
f
D
o
g
[
] orro
y
o
b
j
e
c
f
inf
Sfring
reme
CoIIor
tel
D
o
g
ob
j
e
c
f
:ite
"Fido"
C
o
I
I
o
r
ob
j
e
c
f
S
f
r
i
n
g o
b
j
e
c
f
inf
Sfring
reme
CoIIor
tel
D
o
g
ob
j
e
c
f
:ite
"Spike"
This IenneI objecf hos o reference fo o Dog [] orroy objecf. The
Dog [] hoIds references fo fwo Dog objecfs. Eoch Dog objecf hoIds
o reference fo o Sfring ond o CoIIor objecf. The Sfring objecfs
hove o coIIecfion of chorocfers ond fhe CoIIor objecfs hove on inf.
When you suve the kenneI uII of this is suved|
I
e
n
n
eI o
b
j
e
c
f
Dog [ ]
iej:
Se::a|:zat:aa saves the
eat::e ale:t g:ah.
A|| ale:ts :eIe:ea:eJ
ly :astaa:e va::al|es,
sta:t:ag v:th the
ale:t le:ag se::a|:zeJ.
seriaIized objects
!
--]l
- .: l
-
- :.-
- --
-- l
-
--:l
--- l
- r
----| .:
l
- l
: :l
.l
-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 437
|f yee wzn! yeer r|zss !e |c scr|z||zz||c,
|mp|cmcn! 8cr|z||zz||c
Thc Sciializallc inicilacc is Inown as a n.Ie. oi n inicilacc,
lccausc ihc inicilacc uocsn`i havc any mcihous io imlcmcni. Iis
solc uiosc is io announcc ihai ihc class imlcmcniing ii is, wcll,
e..nI..nbIe. In oihci woius, ol|ccis ol ihai iyc aic savcallc ihiough
ihc sciializaiion mcchanism. Il any suciclass ol a class is sciializallc,
ihc sulclass is auiomaiically sciializallc cvcn il ihc sulclass uocsn`i
cxliciily ucclaic .Ieer Se..nI..nbIe. This is how inicilaccs always
wo.I. Il youi suciclass IS-A" Sciializallc, you aic ioo).
objectOutputStream.writeObject(myBox);
w
.l--- --: --- M
c1
-|----l
--.|-.|- -- l -|| .| .l ---l--
import java.io.*;
public class Box implements Serializable {
private int width;
private int height;
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
public static void main (String[] args) {
Box myBox = new Box();
myBox.setWidth(50);
myBox.setHeight(20);
try {
FileOutputStream fs = new FileOutputStream(foo.ser);
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(myBox);
os.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
--.|-.|- : - l- ..- .:.-, :-
]-- --- l- ---l
N- --l-: l- -|----l, -l --- ]-- :.]
-|----l: --.|-.|-', l :.]: l- l- )/M,
l': 6r l- :--.|-- --:l: - l: l]-'
|/6 ---.l--: :.- l--- -:-l--:
l-:- l-- .|--: -|| - :.-
c----:l l- . |- -.-- --:--'
l -:l: | l --:-'l, -.- .
--- |- -.-- --:--'
M
.- .- 6-:l6-l-ll--.-
:.-- l- l- :----:l-- :l--.- 1-|| l l- --l- l- --:l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
438 chapter 14
seriaIized objects
8erialization is all or nothing.
Can you imagine what would
happen if some of the ob]ect's
state didn't save correctly?
Either the entire
ob]ect graph is
serialized correctly
or serialization fails.
You can't serialize
a Pond ob]ect if
its Duck instance
variable refuses to
be serialized {by
not implementing
8erializable}.
Eeewwwl Thof
creeps me ouf jusf fhinking
obouf ifl Like, whof if o Dog comes
bock wifh no weighf. Or no eors. Or
fhe coIIor comes bock si;e 3 insfeod
of 30. Thof jusf con'f be oIIowedl
import java.io.*;
public class Pond implements Serializable {
private Duck duck = new Duck();
public static void main (String[] args) {
Pond myPond = new Pond();
try {
FileOutputStream fs = new FileOutputStream(Pond.ser);
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(myPond);
os.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
c|.:: |-- .: --- -:l.-:-
.-.|-, . l-:
w-- ]-- :--.|-- -]|-- |. |-- --:l`, l: l-: -:l.-:- .-.|- .-l--.l:.||] -l: :--.|--
public class Duck {
// duck code here
}
/-:'' l-: : --l :--.|-.|-'
|l --:-'l -|----l --.|-.|-,
:- --- ]-- l-] l- :--.|-- .
|-- --:l, l .|: -:.-:- l-
|--': l-: -:l.-:- .-.|-
:.-'l - :.-
|-- --:l: :.- - :--.|--
File Edit Window Help Regret
% java Pond
java.io.NotSerializableException: Duck
at Pond.main(Pond.java:13)
w-- ]-- l-] l- --- l- -.- - :|.:: |--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 439
Mark an instance variable as transient
if it can't {or shouldn't} be saved.
Il you wani an insiancc vaiiallc io lc sIicu ly ihc
sciializaiion ioccss, maiI ihc vaiiallc wiih ihc transient
Icywoiu.
import java.net.*;
class Chat implements Serializable {
transient String currentID;
String userName;
// more code
}
l-.-:--l :.]:, --'l
:.- l: .-.|- ---
:--.|-.l--, -:l : l'
-:--N.-- .-.|-
-|| - :.- .: .-l
- l- --:l': :l.l-
--- :--.|-.l--
If's hopeIess,
fhen7 I'm compIefeIy
screwed if fhe idiof who
wrofe fhe cIoss for my insfonce
voriobIe forgof fo moke if
SerioIi;obIe7
Il you havc an insiancc vaiiallc ihai can`i lc savcu lccausc
ii isn`i sciializallc, you can maiI ihai vaiiallc wiih ihc
iiansicni Icywoiu anu ihc sciializaiion ioccss will sIi iighi
ovci ii.
So why woulu a vaiiallc noi lc sciializallc. Ii coulu lc
ihai ihc class ucsignci simly io maIc ihc class
imlcmcni Sciializallc. Oi ii mighi lc lccausc ihc ol|cci
iclics on iuniimc-sccihc inloimaiion ihai simly can`i lc
savcu. Alihough mosi ihings in ihc ]ava class liliaiics aic
sciializallc, you can`i savc ihings liIc nciwoiI conncciions,
ihicaus, oi hlc ol|ccis. Thcy`ic all uccnucni on anu
sccihc io) a aiiiculai iuniimc cxciicncc`. In oihci woius,
ihcy`ic insianiiaicu in a way ihai`s uniquc io a aiiiculai iun
ol youi iogiam, on a aiiiculai lailoim, in a aiiiculai
]VM. Oncc ihc iogiam shuis uown, ihcic`s no way io liing
ihosc ihings lacI io lilc in any mcaninglul way, ihcy havc io
lc cicaicu liom sciaich cach iimc.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
440 chapter 14
q.
If seriaIization is so important,
why isn't it the defauIt for aII cIasses!
Why doesn't cIass Dbject impIement
SeriaIizabIe, and then aII subcIasses
wiII be automaticaIIy SeriaIizabIe.
[. Lven though most classes will,
and should, implement Serializable,
you always have a choice. And you
must make a conscious decision on
a class-by-class basis, for each class
you design, to 'enable' serialization
by implementing Serializable.
Pirst of all, if serialization were the
default, how would you turn it offI
|nterfaces indicate functionality, not
a locl of functionality, so the model
of polymorphism wouldn't work
correctly if you had to say, "implements
NonSerializable to tell the world that
you cannot be saved.
q.
Why wouId I ever write a cIass
that wnsnr seriaIizabIe!
[. There are very few reasons, but
you might, for example, have a security
issue where you don't want a password
ob|ect stored. Or you might have an
ob|ect that makes no sense to save,
because its key instance variables are
themselves not serializable, so there's
no useful way for you to make yout
class serializable.
q.
If a cIass I'm using isn't
seriaIizabIe, but there's no good
reason (except that the designer just
forgot or was stupid), can I subcIass
the 'bad' cIass and make the subclnss
seriaIizabIe!
[. es! |f the class itself is
extendable (i.e. not final), you can
make a serializable subclass, and |ust
substitute the subclass everywhere
your code is expecting the superclass
type. (Pemember, polymorphism
allows this.) which brings up another
interesting issue: what does it meon if
the superclass is not serializableI
q.
You brought it up: what Jees it
mean to have a seriaIizabIe subcIass
of a non-seriaIizabIe supercIass!
[. Pirst we have to look at what
happens when a class is deserialized,
(we'll talk about that on the next few
pages). |n a nutshell, when an ob|ect
is deserialized and its superclass is not
serializable, the superclass constructor
will run |ust as though a new ob|ect of
that type were being created. |f there's
no decent reason for a class to not
be serializable, making a serializable
subclass might be a good solution.
q.
Whoal I just reaIized
something big... if you make a
variabIe 'transient', this means the
variabIe's vaIue is skipped over
during seriaIization. 7hen what
happens to it! We soIve the probIem
of having a non-seriaIizabIe instance
variabIe by making the instance
variabIe transient, but don't we ND
that variabIe when the object is
brought back to Iife! In other words,
isn't the whoIe point of seriaIization
to preserve an object's state!
[. es, this is an issue, but
fortunately there's a solution. |f you
serialize an ob|ect, a transient reference
instance variable will be brought back
as null, regardless of the value it had
at the time it was saved. That means
the entire ob|ect graph connected to
that particular instance variable won't
be saved. This could be bad, obviously,
because you probably need a non-null
value for that variable.
ou have two options:
l) when the ob|ect is brought back,
reinitialize that null instance variable
back to some default state. This
works if your deserialized ob|ect isn't
dependent on a particular value for
that transient variable. |n other words,
it might be important that the Dog
have a Collar, but perhaps all Collar
ob|ects are the same so it doesn't
matter if you give the resurrected Dog
a brand new Collar, nobody will know
the difference.
2) |f the value of the transient variable
Joes matter (say, if the color and design
of the transient Collar are unique for
each Dog) then you need to save the
key values of the Collar and use them
when the Dog is brought back to
essentially re-create a brand new Collar
that's identical to the original.
q.
What happens if two objects in
the object graph are the same object!
Like, if you have two different Cat
objects in the kenneI, but both Cats
have a reference to the same Dwner
object. Does the Dwner get saved
twice! I'm hoping not.
[. Lxcellent question! Serialization
is smart enough to know when two
ob|ects in the graph are the same. |n
that case, only one of the ob|ects is
saved, and during deserialization, any
references to that single ob|ect are
restored.
seriaIized objects
,-,- a,- |
oa|| qa--,.|-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 441
Pcscr|z||zz!|en: rcs!er|n] zn e|jcr!
Thc wholc oini ol sciializing an ol|cci is so ihai you can
icsioic ii lacI io iis oiiginal siaic ai somc laici uaic, in a
uillcicni iun` ol ihc ]VM which mighi noi cvcn lc ihc samc
]VM ihai was iunning ai ihc iimc ihc ol|cci was sciializcu).
Dcsciializaiion is a loi liIc sciializaiion in icvcisc.
FileInputStream leStream = new FileInputStream(MyGame.ser);
M
.- . ||-|--ll--.- --:l 1- ||-|--ll--.-
---: -- l- :----:l l- .- -:l- |-
Muke u FiIeInputStreum
Object one = os.readObject();
Object two = os.readObject();
Object three = os.readObject();
Muke un ObjectInputStreum
6-:l|--ll--.- |-l: ]-- --. --:l:,
-l l :.-'l --:l|] :----:l l- . |-
|l ---: l- - :.-- l- . :----:l--
:l--.-, - l: :.:- . ||-|--ll--.-
GameCharacter elf = (GameCharacter) one;
GameCharacter troll = (GameCharacter) two;
GameCharacter magician = (GameCharacter) three;
---- -o
l]- !|
--.--: --,
:---, -:l
---- |io
l]- M.:.-
--.--: :-||:,
-:|l]
---- ioo
l]- 1--||
--.--: .--
.-:, .
seriaIization exampIe
w- :-l l-- l- --|| :- -- :.-'l
.::-:: l- --:l: -- l- -.
M.- :--- :.-.:l--:
N-- --. l-- .: - --- l- |-
c-: l- :-- l ----
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 445
import java.io.*;
public class GameCharacter implements Serializable {
int power;
String type;
String[] weapons;
public GameCharacter(int p, String t, String[] w) {
power = p;
type = t;
weapons = w;
}
public int getPower() {
return power;
}
public String getType() {
return type;
}
public String getWeapons() {
String weaponList = ;
for (int i = 0; i < weapons.length; i++) {
weaponList += weapons[i] + ;
}
return weaponList;
}
}
Ihc 0zmc0hzrzr!cr r|zss
1: : . .:: :|.:: -:l -- l-:l-
--.|-.l--, .- -- --'l .- .-
.:l-.| .--, -l --'|| |-.- l.l l-
]-- l- ------l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
saving objects
446 chapter 14
8ll P0lk5
You car save ar oojecl's slale oy ser|a||z|r l|e oojecl.
To ser|a||ze ar oojecl, you reed ar 0ojecl0ulpul3lrear (lror l|e
java.|o pac|ae)
3lrears are e|l|er correcl|or slrears or c|a|r slrears
Correcl|or slrears car represerl a correcl|or lo a source or
desl|ral|or, lyp|ca||y a l||e, relWor| soc|el correcl|or, or l|e
corso|e.
C|a|r slrears carrol correcl lo a source or desl|ral|or ard rusl
oe c|a|red lo a correcl|or (or ol|er) slrear.
To ser|a||ze ar oojecl lo a l||e, ra|e a F||e0upul3lrear ard c|a|r |l
|rlo ar 0ojecl0ulpul3lrear.
To ser|a||ze ar oojecl, ca|| ur|reDojeor{rneDojeorj or l|e
0ojecl0ulpul3lrear. You do rol reed lo ca|| rel|ods or l|e
F||e0ulpul3lrear.
To oe ser|a||zed, ar oojecl rusl |rp|ererl l|e 3er|a||zao|e |rlerlace.
ll a superc|ass ol l|e c|ass |rp|ererls 3er|a||zao|e, l|e suoc|ass W|||
auloral|ca||y oe ser|a||zao|e ever |l |l does rol spec|l|ca||y dec|are
|m|emenrs $er|a||zao|e.
w|er ar oojecl |s ser|a||zed, |ls erl|re oojecl rap| |s ser|a||zed. T|al
rears ary oojecls relererced oy l|e ser|a||zed oojecl's |rslarce
var|ao|es are ser|a||zed, ard ary oojecls relererced oy l|ose
oojecls...ard so or.
ll ary oojecl |r l|e rap| |s rol ser|a||zao|e, ar excepl|or W||| oe
l|roWr al rurl|re, ur|ess l|e |rslarce var|ao|e relerr|r lo l|e oojecl
|s s||pped.
Var| ar |rslarce var|ao|e W|l| l|e rrans|enr |eyWord |l you Warl
ser|a||zal|or lo s||p l|al var|ao|e. T|e var|ao|e W||| oe reslored as ru||
(lor oojecl relererces) or delau|l va|ues (lor pr|r|l|ves).
0ur|r deser|a||zal|or, l|e c|ass ol a|| oojecls |r l|e rap| rusl oe
ava||ao|e lo l|e JvV.
You read oojecls |r (us|r read0ojecl()) |r l|e order |r W||c| l|ey
Were or||ra||y Wr|ller.
T|e relurr lype ol read0ojecl() |s lype 0ojecl, so deser|a||zed
oojecls rusl oe casl lo l|e|r rea| lype.
3lal|c var|ao|es are rol ser|a||zedl ll doesr'l ra|e serse lo save
a slal|c var|ao|e va|ue as parl ol a spec|l|c oojecl's slale, s|rce a||
oojecls ol l|al lype s|are or|y a s|r|e va|uel|e ore |r l|e c|ass.
0le:t Se:ia|izatiaa
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 447
Wr| !|n] z 8!r|n] !e z Icr! I||c
Saving ol|ccis, ihiough sciializaiion, is ihc casicsi way io savc anu
icsioic uaia lciwccn iunnings ol a ]ava iogiam. Bui somciimcs you
nccu io savc uaia io a lain olu icxi hlc. Imaginc youi ]ava iogiam
has io wiiic uaia io a simlc icxi hlc ihai somc oihci cihas non-
]ava) iogiam nccus io icau. You mighi, loi cxamlc, havc a scivlci
]ava couc iunning wiihin youi wcl scivci) ihai iaIcs loim uaia ihc
usci iycu inio a liowsci, anu wiiics ii io a icxi hlc ihai somclouy clsc
loaus inio a sicaushcci loi analysis.
Wiiiing icxi uaia a Siiing, aciually) is similai io wiiiing an ol|cci,
cxcci you wiiic a Siiing insicau ol an ol|cci, anu you usc a
IilcWiiici insicau ol a IilcOuiuiSiicam anu you uon`i chain ii io an
Ol|cciOuiuiSiicam).
b0,Ill,rcw, swcra,aus|
800,1rcll,rare hanas,ri ax
180,Haician,sells,invisirili|y
w.l l- .-- :.-.:l-- .l.
-l |-- |- ]-- ---l- l
--l .: . --.-~--..|- l-l |-
To write u seriuIized object:
objectOutputStream.writeObject(someObject);
To write u String:
leWriter.write(My rst String to save);
import java.io.*;
class WriteAFile {
public static void main (String[] args) {
try {
FileWriter writer = new FileWriter(Foo.txt);
writer.write(hello foo!);
writer.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
w- --- l- ..- .:.- -- ||-w-l--
A
|
|
l- |/6 :l-
--:l - - . l-]/:.l:
!--]l- :.- l--- .-
|6!:-l--''
| l- |- |--ll' --: --l
-:l, ||-w
-l-- -|| :--.l- l
1- --l-|` --l- l.-:
. l--
c|-:- l --- ]--'-- ---'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
448 chapter 14
writing a text fiIe
Icr! I||c Irzmp|c: c-I|zshrzr4s
Rcmcmlci ihosc uashcaius you uscu in school. Whcic you
hau a qucsiion on onc siuc anu ihc answci on ihc lacI.
Thcy aicn`i much hcl whcn you`ic iiying io unucisianu
somcihing, lui noihing lcais cm loi iaw uiill-anu-iaciicc
anu ioic mcmoiizaiion. VLer ,ou Ln.e o bu.r .r n n. Anu
ihcy`ic also gicai loi iiivia gamcs.
Wc'rc going to makc an clcctronic vcrsion that has thrcc
classcs:
1) QuizCordBuiIder, a simlc auihoiing iool loi cicaiing anu
saving a sci ol c-Ilashcaius.
2) QuizCordPIoyer, a laylacI cnginc ihai can loau a
uashcaiu sci anu lay ii loi ihc usci.
S) QuizCord, a simlc class icicscniing caiu uaia. Wc`ll
walI ihiough ihc couc loi ihc luiluci anu ihc layci, anu
havc you maIc ihc QuizCaiu class youiscll, using ihis
w
.l': l- -:l
---- :---l-] --
:--l - l
-l--l
M
:.-
c.-.. |6-l.--`
---l
.:
-|~.:--- ? -
-- |.::.-:
QuizCurduiIder
Hos o FiIe menu wifh o "Sove" opfion for soving
fhe currenf sef of cords fo o fexf fIe.
QuizCurdPIuyer
Hos o FiIe menu wifh o "Lood" opfion for Iooding o
sef of cords from o fexf fIe.
0u|zCard(q, a)
quesl|or
arsWer
el0uesl|or()
elArsWer()
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 449
0e|z 0zr4 Be||4cr |re4c ee!||ncI
ullic class QuizCaiuBuiluci [
ullic voiu go() [
// luilu anu uislay gui
}
iivaic class NcxtCardListcncr imlcmcnis AciionIisicnci [
ullic voiu aciionPciloimcuAciionEvcni cv) [
// auu ihc cuiicni caiu io ihc lisi anu clcai ihc icxi aicas
}
}
iivaic class SavcMcnuListcncr imlcmcnis AciionIisicnci [
ullic voiu aciionPciloimcuAciionEvcni cv) [
// liing u a hlc uialog lox
// lci ihc usci namc anu savc ihc sci
}
}
iivaic class NcwMcnuListcncr imlcmcnis AciionIisicnci [
ullic voiu aciionPciloimcuAciionEvcni cv) [
// clcai oui ihc caiu lisi, anu clcai oui ihc icxi aicas
}
}
iivaic voiu savcFilc(Filc hlc) [
// iiciaic ihiough ihc lisi ol caius, anu wiiic cach onc oui io a icxi hlc
// in a aiscallc way in oihci woius, wiih clcai scaiaiions lciwccn aiis)
}
}
B-|: .- :|.]: l- 6c|, -:|--
-.- .- --:l--- ---l |:l----:
1---- --- -:-- l: 'N-l c.-' -ll--.
--.-: l- -:-- -.-l: l- :l--- l.l :.- -
l- |:l .- :l.-l . --- :.-
1---- --- -:- :--:-: '.-' --- l-
||- ----. --.-: l- -:-- -.-l: l- :.- .||
l- :.-: - l- :-----l |:l .: . ':-l' ||-,
6-.-l-- M-:.-:: -l, +-||]--- 1-.,
).. -|-:, -l:`
1---- ] :--:- 'N--' --- l- ||-
----. --.-: l- -:-- -.-l: l- :l.-l .
-.- --- :-l |:- -- :|-.- --l l- :.-
|:l .- l- l-l .--.:`
c.||- ] l- .-M---|:l----.
--: l- .:l-.| |- --l-
|---- :|.::
|---- :|.::
|---- :|.::
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
450 chapter 14
Quiz Card BuiIder code
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class QuizCardBuilder {
private JTextArea question;
private JTextArea answer;
private ArrayList<QuizCard> cardList;
private JFrame frame;
public static void main (String[] args) {
QuizCardBuilder builder = new QuizCardBuilder();
builder.go();
}
public void go() {
// build gui
frame = new JFrame(Quiz Card Builder);
JPanel mainPanel = new JPanel();
Font bigFont = new Font(sanserif, Font.BOLD, 24);
question = new JTextArea(6,20);
question.setLineWrap(true);
question.setWrapStyleWord(true);
question.setFont(bigFont);
JScrollPane qScroller = new JScrollPane(question);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
answer = new JTextArea(6,20);
answer.setLineWrap(true);
answer.setWrapStyleWord(true);
answer.setFont(bigFont);
JScrollPane aScroller = new JScrollPane(answer);
aScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
aScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
JButton nextButton = new JButton(Next Card);
cardList = new ArrayList<QuizCard>();
JLabel qLabel = new JLabel(Question:);
JLabel aLabel = new JLabel(Answer:);
mainPanel.add(qLabel);
mainPanel.add(qScroller);
mainPanel.add(aLabel);
mainPanel.add(aScroller);
mainPanel.add(nextButton);
nextButton.addActionListener(new NextCardListener());
JMenuBar menuBar = new JMenuBar();
JMenu hleMenu = new JMenu(File);
JMenuItem newMenuItem = new JMenuItem(New);
1: : .|| 6c| :-- --- N-l-
:-:.|, .|l-- ]-- -l -.-l
l- |-- .l l- M
---B.-, M
---,
.- M
---|l--: :--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 451
JMenuItem saveMenuItem = new JMenuItem(Save);
newMenuItem.addActionListener(new NewMenuListener());
saveMenuItem.addActionListener(new SaveMenuListener());
hleMenu.add(newMenuItem);
hleMenu.add(saveMenuItem);
menuBar.add(hleMenu);
frame.setJMenuBar(menuBar);
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(500,600);
frame.setVisible(true);
}
public class NextCardListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
QuizCard card = new QuizCard(question.getText(), answer.getText());
cardList.add(card);
clearCard();
}
}
public class SaveMenuListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
QuizCard card = new QuizCard(question.getText(), answer.getText());
cardList.add(card);
JFileChooser hleSave = new JFileChooser();
hleSave.showSaveDialog(frame);
saveFile(hleSave.getSelectedFile());
}
}
public class NewMenuListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
cardList.clear();
clearCard();
}
}
private void clearCard() {
question.setText();
answer.setText();
question.requestFocus();
}
private void saveFile(File le) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(hle));
for(QuizCard card:cardList) {
writer.write(card.getQuestion() + /);
writer.write(card.getAnswer() + \n);
}
writer.close();
} catch(IOException ex) {
System.out.println(couldn't write the cardList out);
ex.printStackTrace();
}
}
}
B--: - . |- .|- - .- -.l: -- l:
|-- --l| l- -:-- :--:-: '.-' --- l-
.|- - A|| l- |- .|- -..l-- .-
:-|-:l- . |-, -l: : --- -- ]-- ] l-
)||-c--:--' |l --.||] : l: -.:]
1- --l- l.l --: l- .:l-.| |- --l-
|:.||- ] l- .-M
---|:l----': ---l .-|--`
1- .-----l : l- '||-' --:l l- -:-- : :.-
w
-'|| |-- .l l- ||- :|.:: -- l- --l .-
w- :.- . B----w-l-- -- l- . ---
||-w-l-- l- -.- --l- ---- -:--l
|w-'|| l.| .--l l.l - . -- .-:`
w.| l--- l- A--.]|:l -
:.-: .- --l- l-- --l, --- :.- -- |--, -l l- --:l-- .- .-~ :--- :-.-.l- ] . /', .- l-- . . ---|-- :.-.:l-- |`-'`
w- -.- . ---- .-, -.- . ||-
----, l-- -l '---' .- ':.-' ----
l--: -l- l- ||- ---- w- . l-
---- l- l- ---- .-, l-- l-|| l-
-.-- l- -:- l: ---- .- M---
l--: :.- -- .- A:l--!--l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
452 chapter 14
Ihc jzvz.|e.I||c r|zss
Thc |ava.io.Iilc class .e.eer a hlc on uisI, lui uocsn`i
aciually icicscni ihc orer ol ihc hlc. Whai. ThinI ol
a Iilc ol|cci as somcihing moic liIc a nLrne ol a hlc
oi cvcn a J..eo.,) iaihci ihan Thc Aciual Iilc Iiscll.
Thc Iilc class uocs noi, loi cxamlc, havc mcihous loi
icauing anu wiiiing. Onc VERY usclul ihing aloui a Iilc
ol|cci is ihai ii ollcis a much salci way io icicscni a
hlc ihan |usi using a Siiing hlc namc. Ioi cxamlc, mosi
classcs ihai iaIc a Siiing hlc namc in ihcii consiiucioi
liIc IilcWiiici oi IilcInuiSiicam) can iaIc a Iilc
ol|cci insicau. You can consiiuci a Iilc ol|cci, vciily
ihai you`vc goi a valiu aih, cic. anu ihcn givc ihai Iilc
ol|cci io ihc IilcWiiici oi IilcInuiSiicam.
writing fiIes
b0,Ill,rcw, swcra,aus|
800,1rcll,rare hanas,ri ax
180,Haician,sells,invisirili|y
A File ob]ect represents the name
and path of a hle or directory on
disk, for example:
/Users/Kathy/ Data/GameFile.txt
But it does NOT represent, or give
you access to, the data in the hlel
8ome things you can do with a File ob]ect:
GameFile.txt
A ||- --:l --: N61
----:--l |-- - ]--
--:l .::-:: l-` l-
.l. -:- l- |-'
A ||- --:l ----:--l: l-
|--.-- 6.--||-ll'
File f = new File(MyCode.txt);
Muke u FiIe object representing un
eisting hIe
1
File dir = new File(Chapter7);
dir.mkdir();
Muke u new directory 2
if (dir.isDirectory()) {
String[] dirContents = dir.list();
for (int i = 0; i < dirContents.length; i++) {
System.out.println(dirContents[i]);
}
}
List the contents of u directory 3
System.out.println(dir.getAbsolutePath());
Set the ubsoIute puth of u hIe or directory 4
boolean isDeleted = f.delete();
DeIete u hIe or directory {returns true if
successfuI}
5
A- .--:: : N61 l-
:.-- .: l- .:l-.|
--:-' A ||- --:l :
|- . :l---l .--::
l ----:--l: l- -.--
.- |-:.l-- - . .-~
l:-|.- |-, -l l :-'l
l- |- l:-|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
seriaIization and fiIe I/O
you are here 453
Sfring
8ufferedWrifer
(o choin sfreom fhof
works wifh chorocfers)
is wriffen fo
Sfring is puf info o buffer
wifh ofher Sfrings
FiIeWrifer
(o connecfion sfreom
fhof wrifes chorocfers
os opposed fo byfes)
"Aspen Denver 8ouIder"
When fhe buffer is fuII, fhe
Sfrings ore oII wriffen fo
Aspen
Denver
8ouIder
FiIe
-:l-.l--
is choined fo
8ealder"
8ealder"
0enver"
Aspen"
The beauty of buffers
If there were no buffers it wouId be Iike
shopping without u curt, You'd huve to
curry euch thing out to your cur one soup
cun or toiIet puper roII ut u time,
Thc cool ihing aloui lullcis is ihai ihcy`ic uL moic clhcicni ihan
woiIing wiihoui ihcm. You can wiiic io a hlc using IilcWiiici alonc, ly
calling wiiicsomcSiiing), lui IilcWiiici wiiics cach anu cvciy ihing you
ass io ihc hlc cach anu cvciy iimc. Thai`s ovcihcau you uon`i wani oi
nccu, sincc cvciy iii io ihc uisI is a Big Dcal comaicu io maniulaiing
uaia in mcmoiy. By chaining a BullcicuWiiici onio a IilcWiiici, ihc
BullcicuWiiici will holu all ihc siull you wiiic io ii uniil ii`s lull. OrI, wLer
Le bue. . uII w.II Le E.IeV..e. nunII, be oIJ o w..e o Le Ie or J.I.
Il you uo wani io scnu uaia beo.e ihc lullci is lull, you uo havc coniiol.
]ust FIush It. Calls io wiiici.uush) say, scnu whaicvci`s in ihc lullci, now!"
---: - ]-- . l----.-] -|-
|.:- l- --- l-: --l| l- -|--
||- l- :.-l` : -|| /-- -l l- -.-
.- ---- l-: --- ]-- -:- . ---
BufferedWriter writer = new BufferedWriter(new FileWriter(aFile));
N-l:- l.l -- --'l ---
--- l- -- . ------:- l-
l- ||-w-l-- --:l 1-
--|] l- -- :.-- .--l : l-
B----w-l--, -:.-:- l.l':
l- --:l --'|| :.|| --l-:
--, .- --- -- :|-:- l-
B----w-l--, l -|| l.-
:.-- - l- --:l - l- :.-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
454 chapter 14
Kcz4|n] frem z Icr! I||c
Rcauing icxi liom a hlc is simlc, lui ihis iimc wc`ll usc a Iilc
ol|cci io icicscni ihc hlc, a IilcRcauci io uo ihc aciual icauing,
anu a BullcicuRcauci io maIc ihc icauing moic clhcicni.
Thc icau hacns ly icauing lincs in a loo, cnuing ihc loo
whcn ihc icsuli ol a icauIinc) is null. Thai`s ihc mosi common
siylc loi icauing uaia iciiy much anyihing ihai`s noi a Sciializcu
ol|cci): icau siull in a whilc loo aciually a whilc loo ),
iciminaiing whcn ihcic`s noihing lcli io icau which wc Inow
lccausc ihc icsuli ol whaicvci icau mcihou wc`ic using is null).
Tha|`s 8 + 8?/4
Tha|`s 80+88/48
A |- -l l-- |--: - l-l
import java.io.*;
class ReadAFile {
public static void main (String[] args) {
try {
File myFile = new File(MyText.txt);
FileReader leReader = new FileReader(myFile);
BufferedReader reader = new BufferedReader( leReader);
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
l--'l ---l l- ---l
c.- l- ||--.-- l- .
B
-----.-- -- ----
-:--l --.- |l'|| - .:
l- l- |- l- --. --|] ---
l- --- : --l] |-:.-:- l-
---.- .: --. ---]l- - l`
A ||--.-- : . :----:l-- :l--.- -- :.-.:l--:, l.l :----:l: l- . l-l |-
M.- . l-- .-.|- l- -|
-.: |-- .: l- |-- : --.
reading fiIes
:|.:: --:-- :
+
7i
5
SeroiIi;ofion foiIsll
The JVM soys, "you con'f
feoch on oId Dog new code".
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 461
Each iimc an ol|cci is sciializcu, ihc ol|cci incluuing
cvciy ol|cci in iis giah) is siamcu` wiih a vcision
ID numlci loi ihc ol|cci`s class. Thc ID is callcu
ihc sciialVcisionUID, anu ii`s comuicu lascu on
inloimaiion aloui ihc class siiuciuic. As an ol|cci is
lcing ucsciializcu, il ihc class has changcu sincc ihc
ol|cci was sciializcu, ihc class coulu havc a uillcicni
sciialVcisionUID, anu ucsciializaiion will lail! Bui you
can coniiol ihis.
f you think there is ANY possibility that
your class might evolve, put a serial version
D in your class.
Whcn ]ava iiics io ucsciializc an ol|cci, ii comaics
ihc sciializcu ol|cci`s sciialVcisionUID wiih ihai ol ihc
class ihc ]VM is using loi ucsciializing ihc ol|cci. Ioi
cxamlc, il a Dog insiancc was sciializcu wiih an ID ol,
say 2S in icaliiy a sciialVcisionUID is much longci),
whcn ihc ]VM ucsciializcs ihc Dog ol|cci ii will hisi
comaic ihc Dog ol|cci sciialVcisionUID wiih ihc
Dog class sciialVcisionUID. Il ihc iwo numlcis uon`i
maich, ihc ]VM assumcs ihc class is noi comaiillc
wiih ihc icviously-sciializcu ol|cci, anu you`ll gci an
cxcciion uuiing ucsciializaiion.
So, ihc soluiion is io ui a sciialVcisionUID
in youi class, anu ihcn as ihc class cvolvcs, ihc
sciialVcisionUID will icmain ihc samc anu ihc ]VM
will say, OK, cool, ihc class is comaiillc wiih ihis
sciializcu ol|cci." cvcn ihough ihc class has aciually
changcu.
This woiIs il you`ic caiclul wiih youi class
changcs! In oihci woius, aic iaIing icsonsililiiy
loi any issucs ihai comc u whcn an oluci ol|cci is
lioughi lacI io lilc wiih a ncwci class.
To gci a sciialVcisionUID loi a class, usc ihc sciialvci
iool ihai shis wiih youi ]ava ucvclomcni Iii.
0s|n] !hc scr|z|Vcrs|en0|P
File Edit Window Help serialKiller
% serialver Dog
Dog: static final long
serialVersionUID = -
5849794470654667210L;
public class Dog {
static nal long serialVersionUID =
-6849794470754667710L;
private String name;
private int size;
// method code here
}
File Edit Window Help serialKiller
% serialver Dog
Dog: static final long
serialVersionUID = -
5849794470654667210L;
1 Use fhe serioIver commond-Iine fooI
fo gef fhe version ID for your cIoss
2 Posfe fhe oufpuf info your cIoss
3 8e sure fhof when you moke chonges fo
fhe cIoss, you foke responsibiIify in your
code for fhe consequences of fhe chonges
you mode fo fhe cIossl For exompIe, be
sure fhof your new Dog cIoss con deoI wifh
on oId Dog being deserioIi;ed wifh defouIf
voIues for insfonce voriobIes odded fo fhe
cIoss offer fhe Dog wos serioIi;ed.
When you think your class
might evolve after someone has
serialized ob]ects from it...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
462 chapter 14
CaJe kit:hea
Iet's a|e the 5eat5ax save aaJ
:esta:e aa: Iava:ite atte:a
w-- ]-- :|: :--.|--|l',
l- :-----l .ll--- -||
- :.-
--:l---' |-.: l- :.-
.ll--- .: -, .- --:-l:
l- :-:--:
Code Kitchen
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
seriaIization and fiIe I/O
you are here 463
Rcmcmlci, in ihc BcaiBox, a uium aiicin is noihing moic ihan a lunch ol
chccIloxcs. Whcn ii`s iimc io lay ihc scqucncc, ihc couc walIs ihiough ihc
chccIloxcs io hguic oui which uiums sounus aic laying ai cach ol ihc 16
lcais. So io savc a aiicin, all wc nccu io uo is savc ihc siaic ol ihc chccIloxcs.
Wc can maIc a simlc loolcan aiiay, holuing ihc siaic ol cach ol ihc 26
chccIloxcs. An aiiay ol|cci is sciializallc as long as ihc ihings .r ihc aiiay aic
sciializallc, so wc`ll havc no iioullc saving an aiiay ol loolcans.
To loau a aiicin lacI in, wc icau ihc singlc loolcan aiiay ol|cci ucsciializc
ii), anu icsioic ihc chccIloxcs. Mosi ol ihc couc you`vc alicauy sccn, in ihc
Couc Kiichcn whcic wc luili ihc BcaiBox GUI, so in ihis chaici, wc looI ai
only ihc savc anu icsioic couc.
This CoucKiichcn gcis us icauy loi ihc ncxi chaici, whcic insicau ol wiiiing
ihc aiicin io a Ie, wc scnu ii ovci ihc rewo.I io ihc scivci. Anu insicau ol
loauing a aiicin .r liom a hlc, wc gci aiicins liom ihc e..e., cach iimc a
aiiiciani scnus onc io ihc scivci.
8erializing a pattern
8zv|n] z Bcz!Ber pz!!crn
public class MySendListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
boolean[] checkboxState = new boolean[256];
for (int i = 0; i < 256; i++) {
JCheckBox check = (JCheckBox) checkboxList.get(i);
if (check.isSelected()) {
checkboxState[i] = true;
}
}
try {
FileOutputStream leStream = new FileOutputStream(new File(Checkbox.ser));
ObjectOutputStream os = new ObjectOutputStream(leStream);
os.writeObject(checkboxState);
} catch(Exception ex) {
ex.printStackTrace();
}
} // close method
} // close inner class
|l .|| .--: --- l- -:-- :|:: l-
-ll-- .- l- A:l--!--l --:
1: : .- ---- :|.:: -:-
l- B-.lB- :--
M.- . --|-.- .--.] l- -| l- :l.l- - -.: :-:-
w.| l--- l- :-:-|:l |A--.]|:l - :-:--:`, .- -l l- :l.l- - -.: ---, .- . l l- l- --|-.- .--.]
1: .-l': . -:- - :.- )-:l --l-/:--.|-- l- --- --|-.- .--.]'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
464 chapter 14
This is iciiy much ihc savc in icvcisc... icau ihc loolcan aiiay anu usc ii
io icsioic ihc siaic ol ihc GUI chccIloxcs. Ii all hacns whcn ihc usci hiis
ihc icsioic" luiion.
Restoring a pattern
Kcs!er|n] z Bcz!Ber pz!!crn
public class MyReadInListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
boolean[] checkboxState = null;
try {
FileInputStream leIn = new FileInputStream(new File(Checkbox.ser));
ObjectInputStream is = new ObjectInputStream(leIn);
checkboxState = (boolean[]) is.readObject();
} catch(Exception ex) {ex.printStackTrace();}
for (int i = 0; i < 256; i++) {
JCheckBox check = (JCheckBox) checkboxList.get(i);
if (checkboxState[i]) {
check.setSelected(true);
} else {
check.setSelected(false);
}
}
sequencer.stop();
buildTrackAndStart();
} // close method
} // close inner class
1: : .--l-- ---- :|.::
-:- l- B-.lB- :|.::
-. l- :-|- --:l - l- |- |l-
--|-.- .--.]` .- :.:l l .: l- .
--|-.- .--.] |-------, --.6-:l|`
--l---: . ------:- - l]- 6-:l
N-- --:l--- l- :l.l- - -.: - l-
:-:--: - l- A--.]|:l - .:l-.|
)c-:B- --:l: |:-:-|:l`
N-- :l- -.l--- : :-----l|] |.]-,
.- ---| l- :----:- -:- l- ---
:l.l- - l- :-:--: - l- A--.]|:l
deseriaIizing the pattern
+,-+ :+ ,-+:.|
This version has a huge limitation! when you hit the "serialize|t button, it
serializes automatically, to a file named "Checkbox.ser (which gets created if it
doesn't exist). 8ut each time you save, you overwrite the previously-saved file.
|mprove the save and restore feature, by incorporating a 1PileChooser so that
you can name and save as many different patterns as you like, and load/restore
from of your previously-saved pattern files.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 465
which of these do you think are, or should be,
serializableI |f not, why notI Not meaningfulI
Security riskI Only works for the current
execution of the 1vMI Make your best guess,
without looking it up in the AP|.
(zn ([y ,zv]/
Ob]ect type 8erializable? f not, why not?
Object Yes / No ______________________________________
String Yes / No ______________________________________
File Yes / No ______________________________________
Date Yes / No ______________________________________
OutputStream Yes / No ______________________________________
JFrame Yes / No ______________________________________
nteger Yes / No ______________________________________
System Yes / No ______________________________________
N08l`8 l08lF
C|rc|e l|e code lrarerls
l|al Wou|d corp||e (assur|r
l|ey're W|l||r a |ea| c|ass).
FileReader leReader = new FileReader();
BufferedReader reader = new BufferedReader(leReader);
FileOutputStream f = new FileOutputStream(new File(Foo.ser));
ObjectOutputStream os = new ObjectOutputStream(f);
BufferedReader reader = new BufferedReader(new FileReader(le));
String line = null;
while ((line = reader.readLine()) != null) {
makeCard(line);
}
ObjectInputStream is = new ObjectInputStream(new FileOutputStream(Game.ser));
GameCharacter oneAgain = (GameCharacter) is.readObject();
+,-+ :+ ,-+:.|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
466 chapter 14
exercise soIutions
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
seriaIization and fiIe I/O
you are here 469
File Edit Window Help Escape
% java DungeonTest
12
8
import ava.io.*,
class DungeonGame implements Serializable {
public int x = 3,
transient long y = 4,
private short z = 5,
int getX{| {
return x,
}
long getY{| {
return y,
}
short getZ{| {
return z,
}
}
class DungeonTest {
public static void main{String args| {
DungeonGame d = new DungeonGame{|,
System.out.println{d.getX{| + d.getY{| + d.getZ{||,
try {
FileOutputStream fos = new FileOutputStream{"dg.ser"|,
ObectOutputStream oos = new ObectOutputStream{fos|,
oos.writeObect{d|,
oos.close{|,
FileInputStream s = new FileInputStream{"dg.ser"|,
ObectInputStream ois = new ObectInputStream{s|,
d = {DungeonGame| ois.readObect{|,
ois.close{|,
} catch {Exception e| {
e.printStackTrace{|,
}
System.out.println{d.getX{| + d.getY{| + d.getZ{||,
}
}
0ood fhing we're
fnoIIy of fhe onswers.
I wos geffin' kind of
fired of fhis chopfer.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Make a Connection
15 networking and threads
Connect with the outside worId. our 1ava program can reach out and touch a
program on another machine. |t's easy. All the low-level networking details are taken care of by
classes in the |ava.net library. One of 1ava's big benefits is that sending and receiving data over
a network is |ust |/O with a slightly different connection stream at the end of the chain. |f you've
got a 8ufferedPeader, you can teoJ. And the 8ufferedPeader could care less if the data came
out of a file or flew down an ethernet cable. |n this chapter we'll connect to the outside world
with sockets. we'll make cl|ent sockets. we'll make setvet sockets. we'll make cl|ents and setvets.
And we'll make them talk to each other. 8efore the chapter's done, you'll have a fully-functional,
multithreaded chat client. Did we |ust say mult|thteoJeJI es, now you w|ll learn the secret of
how to talk to 8ob while simultaneously listening to Suzy.
this is a new chapter 471
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
472 chapter 15
sky|er4: fast and funky, good for sequence 12
evster2: ||ke sky|er2, but more 0akenfo|d|sh
sky|er5: you w|8h! Too perky
try th|s one... |t's better for
sequence 8
beat box chat
Kcz|-!|mc Bcz! Ber 0hz!
You`ic woiIing on a comuici gamc. You anu youi icam
aic uoing ihc sounu ucsign loi cach aii ol ihc gamc.
Using a chai` vcision ol ihc Bcai Box, youi icam can
collaloiaic-you can scnu a lcai aiicin along wiih
youi chai mcssagc, anu cvciylouy in ihc Bcai Box Chai
gcis ii. So you uon`i |usi gci io .enJ ihc oihci
aiiicianis` mcssagcs, you gci io loau anu
In, a lcai aiicin simly ly clicIing ihc
mcssagc in ihc incoming mcssagcs aica.
In ihis chaici wc`ic going io lcain whai ii
iaIcs io maIc a chai clicni liIc ihis. Wc`ic
cvcn going io lcain a liiilc aloui maIing a
chai e..e.. Wc`ll savc ihc lull Bcai Box Chai
loi ihc Couc Kiichcn, lui in ihis chaici you
w.II wiiic a Iuuiciously Simlc Chai Clicni anu
Vciy Simlc Chai Scivci ihai scnu anu icccivc
icxi mcssagcs.
:|:- -- . --:-- --::.-
|-.: l- .ll--- l.l ---l
-l l
1]- . --::.- .-
--:: l- :--|l -ll--
l- :-- ]--- --::.-
ANl ]--- :-----l -.l
.ll---
/-- :.- .- :--|-l-|]
.-l--l:, -l-||-:l-.||]
:l--|.l- :.l
:----:.l--: !--]
--::.- : :--l l- .||
.-l:.-l:
-- ]--- --::.- l- l- :----
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 473
Why am
here? Don't
expect ME to
answer that.
Why am
here? Don't
expect ME to
answer that.
Why am
here? Don't
expect ME to
answer that.
[[ (]jn( [z, ( [nw
za( ([ v.
[[ v [z, ( [nw
za( jjj ([ (]jn(,.
Chat Program Overview
CIienf A
----, |' |- l- :----:l
l- l- :.l :--:-
CIienf A
6r, ]--'-- -
Part|c|pants:
1. 6||ent A
Why am here?
Don't expect
ME to answer
that. So, why am
CIienf 8
Part|c|pants:
1. 6||ent A
2. 6||ent
Why am here?
Don't expect
ME to answer
that. So, why am
CIienf A
How it Works:
Hessage
rece|ved
8f8l 88f00ll
OK, you got a Socket connection. The client and the
server know the |P address and TCP port number for
each other. Now whatI How do you communicate
over that connectionI |n other words, how do you
move bits from one to the otherI |magine the kinds of
messages your chat client needs to send and receive.
+-- - l-:- l--
.:l-.||] l.| l-
-.: -l--
(-,- a,- |
oa|| qa--(:|-
How do you know the port
number of the server program you
want to taIk to!
That depends on whether the
program is one of the well-known
services. |f you're trying to connect
to a well-known service, like the ones
on the opposite page (HTTP, SMTP,
PTP, etc.) you can look these up on
the internet (Google "well-Known
TCP Port). Or ask your friendly
neighborhood sys-admin.
8ut if the program isn't one of the
well-known services, you need to
find out from whoever is deploying
the service. Ask him. Or her. Typically,
if someone writes a network service
and wants others to write clients for
it, they'll publish the |P address, port
number, and protocol for the service.
Por example, if you want to write a
client for a GO game server, you can
visit one of the GO server sites and
find information about how to write a
client for that particular server.
Can there ever be more than
one program running on a singIe
port! In other words, can two
appIications on the same server have
the same port number!
No! |f you try to bind a program
to a port that is already in use, you'll
get a 8indLxception. To a program
to a port |ust means starting up a
server application and telling it to run
on a particular port. Again, you'll learn
more about this when we get to the
server part of this chapter.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
478 chapter 15
To communicaic ovci a SocIci conncciion, you usc siicams.
Rcgulai olu I/O siicams, |usi liIc wc uscu in ihc lasi chaici. Onc
ol ihc coolcsi lcaiuics in ]ava is ihai mosi ol youi I/O woiI won`i
caic whai youi high-lcvcl chain siicam is aciually connccicu io. In
oihci woius, you can usc a BullcicuRcauci |usi liIc you uiu whcn
you wcic wiiiing io a hlc, ihc uillcicncc is ihai ihc unucilying
conncciion siicam is connccicu io a SoIe iaihci ihan a E.Ie
Ie rcz4 4z!z frem z 8erkc!, esc z
Beffcrc4Kcz4cr
Socket chatSocket = new Socket(127.0.0.1, 5000);
|i7oo| : l- || .--:: -- |-:.|-:l', -
-l-- ---:, l- --- l: :-- : ----- -- /--
:.- -:- l: --- ]--'-- l-:l- ]--- :|--l .-
:---- -- . :-|-, :l.-~.|--- -.:--
Read
:-:-l-l|--ll--.-|`
writing a cIient
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 481
import java.io.*;
import java.net.*;
public class DailyAdviceClient {
public void go() {
try {
Socket s = new Socket(127.0.0.1, 4242);
InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
String advice = reader.readLine();
System.out.println(Today you should: + advice);
reader.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
DailyAdviceClient client = new DailyAdviceClient();
client.go();
}
}
Pz||y4v|rc0||cn! re4c
:|.:: -:-l : - ..--l
-.- . -:-l :----:l-- l- -.l--- :
----- -- --l +i+i, -- l- :.-- -:l
l: :-- : ----- -- |1- '|-:.|-:l'`
. |-l :.- - ---- ---
:.- . B-----.-- l-
.- |--ll--.--.-- l-
l- --l :l--.- --- l-
-:-l
l: --.|--|` : !xAc1|/
l- :.-- .: ]-- ---- -:- .
B-----.-- :.-- l- . |||!
|- -l-- ---:, ] l- l-- ]--
:.|| . B----w-l-- --l-, l-
--l-- --:-'l --- -- :.-- ----
l- :.-.:l--: :.-- ---
l: :|-:-: A|| l- :l--.-:
This progrom mokes o Sockef, mokes o 8ufferedPeoder (wifh fhe
heIp of ofher sfreoms), ond reods o singIe Iine from fhe server
oppIicofion (whofever is running of porf 4Z4Z).
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
socket connections
482 chapter 15
+,-+ :+ ,-+:.|
Test your memory of the streams/classes for reading and writing from a
Socket. Try not to look at the opposite page!
CIient
Server
To text from a Socket:
:---:-
--l-/-.- - l- :.- - :l--.-: l- :|--l
-:-: l- --. --- l- :----
CIient
Server
To text to a Socket:
-:l-.l--
--l-/-.- - l- :.- - :l--.-: l- :|--l
-:-: l- :-- :---l- l- l- :----
+,-+ :+ ,-+:.|
what two pieces of information does the client need in order to make a
Socket connection with a serverI
FiII in the bIanks:
which TCP port numbers are reserved for 'well-known services' like HTTP and PTPI
TPUL or PALSL: The range of valid TCP port numbers can be represented
by a short primitiveI
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 483
Wr| !|n] z s|mp|c scrvcr
So whai`s ii iaIc io wiiic a scivci alicaiion. ]usi a
coulc ol SocIcis. Ycs, a coulc as in . A ScivciSocIci,
which waiis loi clicni icqucsis whcn a clicni maIcs a
ncw SocIci)) anu a lain olu SocIci socIci io usc loi
communicaiion wiih ihc clicni.
-----:-l
-----:-l
-:-l
-----:-l |-.l-
-- l- --l :|--l`
-:-l
-:-l
This sforfs fhe server oppIicofion Iisfening
for cIienf requesfs coming in for porf 4Z4Z.
CIienf knows fhe IP oddress ond porf number
(pubIished or given fo him by whomever
confgures fhe server opp fo be on fhof porf)
The occepf() mefhod bIocks (jusf sifs fhere) whiIe
if's woifing for o cIienf Sockef connecfion. When o
cIienf fnoIIy fries fo connecf, fhe mefhod refurns
o pIoin oId Sockef (on o differenf porf) fhof knows
how fo communicofe wifh fhe cIienf (i.e., knows fhe
cIienf's IP oddress ond porf number). The Sockef is on
o differenf porf fhon fhe ServerSockef, so fhof fhe
ServerSockef con go bock fo woifing for ofher cIienfs.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
484 chapter 15
import java.io.*;
import java.net.*;
public class DailyAdviceServer {
String[] adviceList = {Take smaller bites, Go for the tight jeans. No they do NOT
make you look fat., One word: inappropriate, Just for today, be honest. Tell your
boss what you *really* think, You might want to rethink that haircut.};
public void go() {
try {
ServerSocket serverSock = new ServerSocket(4242);
while(true) {
Socket sock = serverSock.accept();
PrintWriter writer = new PrintWriter(sock.getOutputStream());
String advice = getAdvice();
writer.println(advice);
writer.close();
System.out.println(advice);
}
} catch(IOException ex) {
ex.printStackTrace();
}
} // close go
private String getAdvice() {
int random = (int) (Math.random() * adviceList.length);
return adviceList[random];
}
public static void main(String[] args) {
DailyAdviceServer server = new DailyAdviceServer();
server.go();
}
}
Pz||y4v|rc8crvcr re4c
This iogiam maIcs a ScivciSocIci anu waiis loi clicni icqucsis. Whcn ii gcis
a clicni icqucsi i.c. clicni saiu ncw SocIci) loi ihis alicaiion), ihc scivci
maIcs a ncw SocIci conncciion io ihai clicni. Thc scivci maIcs a PiiniWiiici
using ihc SocIci`s ouiui siicam) anu scnus a mcssagc io ihc clicni.
------- l- ---l:
.|] .:- :---: --- l: .--.]
-----:-l -.-: l: :----
.|:.l-- '|:l--' -- :|--l ----:l:
-- --l +i+i -- l- -.:-- l:
:-- : ----- --
1- :---- --: -l- . ---.---l |--,
-.l- -- |.- :--:-` :|--l ----:l:
l- .::-l --l- |-:: |-:l :l: l---` --l| .
----:l :---: -, .- l-- l- --l- --l---: .
-:-l |-- :--- .---]---: --l` -- :-----:.l-
-l l- :|--l
--- -- -:- l- -:-l :----:l-- l- l- :|--l l-
-.- . |--lw-l-- .- :-- l |--l|-|`` . l--
.:- --::.- 1-- -- :|-:- l- -:-l -:.-:-
--'-- --- -l l: :|--l
writing a server
|-------, l-:- l--:
---- ---~--.- ]
l- :-- -l-- N---
l --l--- - l- -|-
- . l--'`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 485
8ll P0lk5
C||erl ard server app||cal|ors corrur|cale over a 3oc|el
correcl|or.
A 3oc|el represerls a correcl|or oelWeer lWo app||cal|ors
W||c| ray (or ray rol) oe rurr|r or lWo d|llererl p|ys|ca|
rac||res.
A c||erl rusl |roW l|e lP address (or dora|r rare) ard
TCP porl ruroer ol l|e server app||cal|or.
A TCP porl |s a 1-o|l urs|red ruroer ass|red lo a
spec|l|c server app||cal|or. TCP porl ruroers a||oW d|llererl
c||erls lo correcl lo l|e sare rac||re oul corrur|cale
W|l| d|llererl app||cal|ors rurr|r or l|al rac||re.
T|e porl ruroers lror 0 l|rou| 1023 are reserved lor
'We||-|roWr serv|ces' |rc|ud|r lTTP, FTP, 3VTP, elc.
A c||erl correcls lo a server oy ra||r a 3erver soc|el
Socket s = new Socket(127.0.0.1, 4200);
0rce correcled, a c||erl car el |rpul ard oulpul slrears
lror l|e soc|el. T|ese are |oW-|eve| 'correcl|or' slrears.
sock.getInputStream();
To read lexl dala lror l|e server, creale a 8ulleredReader,
c|a|red lo ar lrpul3lrearReader, W||c| |s c|a|red lo l|e
|rpul slrear lror l|e 3oc|el.
lrpul3lrearReader |s a 'or|de' slrear l|al la|es |r
oyles ard corverls l|er lo lexl (c|aracler) dala. ll's used
pr|rar||y lo acl as l|e r|dd|e c|a|r oelWeer l|e |||-|eve|
8ulleredReader ard l|e |oW-|eve| 3oc|el |rpul slrear.
To Wr|le lexl dala lo l|e server, creale a Pr|rlwr|ler c|a|red
d|recl|y lo l|e 3oc|el's oulpul slrear. Ca|| l|e pr|rl() or
pr|rl|r() rel|ods lo serd 3lr|rs lo l|e server.
3ervers use a 3erver3oc|el l|al Wa|ls lor c||erl requesls or
a parl|cu|ar porl ruroer.
w|er a 3erver3oc|el els a requesl, |l 'accepls' l|e requesl
oy ra||r a 3oc|el correcl|or W|l| l|e c||erl.
H
a
S
se
in
H
w
S
S
ca
cl
H
S
B
M
2
It
h
sa
8f8l 88f00ll
Rew Jees rhe server knew hew re
cemmunicnre wirh rhe clienr?
The client knows the |P address and port
number of the server, but how is the server
able to make a Socket connection with the
client (and make input and output streams)I
Think about how / when / where the server
gets knowledge about the client.
(-,- a,- |
oa|| qa--(:|-
Option Three: Read messages as soon as they're sent from the server
Mosi clhcicni, lcsi usaliliiy
Cons: How uo you uo you uo iwo ihings ai ihc samc iimc. Whcic woulu you ui ihis couc.
You`u nccu a loo somcwhcic ihai was always waiiing io icau liom ihc scivci. Bui whcic
woulu ihai go. Oncc you launch ihc GUI, noihing hacns uniil an cvcni is hicu ly a GUI
comoncni.
improving the chat cIient
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 489
You know by now that we're
going with option three.
]n ]zvz ya z]]y (j
wz][ zn] e[w ga z(
([ ,z (j.
Wc wani somcihing io iun coniinuously,
chccIing loi mcssagcs liom ihc scivci,
lui w.Lou .re..u.r Le ue.` nb.I., o
.re.n w.L Le CUI So whilc ihc usci is
haily iying ncw mcssagcs oi sciolling
ihiough ihc incoming mcssagcs, wc
wani somcihing beL.rJ Le ere io Icc
icauing in ncw inui liom ihc scivci.
Thai mcans wc hnally nccu a ncw ihicau.
A ncw, scaiaic siacI
Wc wani cvciyihing wc uiu in ihc Scnu-
Only vcision vcision onc) io woiI ihc
samc way, whilc a ncw .oe iuns along
siuc ihai icaus inloimaiion liom ihc
scivci anu uislays ii in ihc incoming icxi
aica.
Wcll, noi quiic. Unlcss you havc muliilc
ioccssois on youi comuici, cach ncw
]ava ihicau is noi aciually a scaiaic
ioccss iunning on ihc OS. Bui ii almosi
eeI as ihough ii is.
Multithreading in Java
]ava has muliilc ihicauing luili iighi
inio ihc laliic ol ihc languagc. Anu ii`s a
sna io maIc a ncw ihicau ol cxccuiion:
Thread t = new Thread();
t.start();
Thai`s ii. By cicaiing a ncw Thicau obe,
you`vc launchcu a scaiaic L.enJ o
e:eu.or, wiih iis vciy own call siacI.
Except [or one probIem.
Thai ihicau uocsn`i aciually Jo anyihing,
so ihc ihicau uics" viiiually ihc insiani
ii`s loin. Whcn a ihicau uics, iis ncw
siacI uisacais again. Enu ol sioiy.
So wc`ic missing onc Icy comoncni-
ihc ihicau`s ob. In oihci woius, wc nccu
ihc couc ihai you wani io havc iun ly a
scaiaic ihicau.
Muliilc ihicauing in ]ava mcans wc
havc io looI ai loih ihc L.enJ anu ihc ob
ihai`s .ur ly ihc ihicau. Anu wc`ll also
havc io looI ai ihc Thicau In in ihc
|ava.lang acIagc. Rcmcmlci, |ava.lang
is ihc acIagc you gci imoiicu loi
licc, imliciily, anu ii`s whcic ihc classcs
mosi lunuamcnial io ihc languagc livc,
incluuing Siiing anu Sysicm.)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
490 chapter 15
1zvz hzs me| !|p|c !hrcz4s |e! en|y
enc Ihrcz4 r|zss
Wc can ialI aloui L.enJ wiih a lowci-casc i` anu
wiih a caiial T`. Whcn you scc L.enJ, wc`ic ialIing
aloui a scaiaic ihicau ol cxccuiion. In oihci woius,
a scaiaic call siacI. Whcn you scc , ihinI ol
ihc ]ava naming convcniion. Whai, in ]ava, siaiis wiih a
caiial lciici. Classcs anu inicilaccs. In ihis casc,
is a class in ihc |ava.lang acIagc. A ol|cci
icicscnis a L.enJ o e:eu.or, you`ll cicaic an insiancc ol
class cach iimc you wani io siaii u a ncw L.enJ
ol cxccuiion.
thread
run{ }
doStuff{ }
go{ }
doMore{ }
Thread
vo|d jo|r()
vo|d slarl()
slal|c vo|d s|eep()
A ihicau lowci-casc i`) is a scaiaic ihicau ol cxccuiion.
Thai mcans a scaiaic call siacI. Evciy ]ava alicaiion
siaiis u a main ihicau-ihc ihicau ihai uis ihc
main) mcihou on ihc loiiom ol ihc siacI. Thc ]VM
is icsonsillc loi siaiiing ihc main ihicau anu oihci
ihicaus, as ii chooscs, incluuing ihc gailagc collcciion
ihicau). As a iogiammci, you can wiiic couc io siaii
oihci ihicaus ol youi own.
muin{ }
,foo{ }
y,bur{ }
,buz{ }
main thread another thread
started by the code
Thicau caiial T`) is a class ihai
icicscnis a ihicau ol cxccuiion.
Ii has mcihous loi siaiiing a
ihicau, |oining onc ihicau wiih
anoihci, anu uiiing a ihicau io
slcc. Ii has moic mcihous, ihcsc
aic |usi ihc ciucial oncs wc nccu
io usc now).
]ava.lang.Thread
class
j ([z] j, z ,zz(
'([z] | yea(jn'.
]n ([ w],, z
,zz( ez]] ,(ze[.
j [[z] j, z ]zvz
e]z,, ([z( ,n(,
z ([z].
[ z[ z ([z],
z[ z [[z].
threads and Thread
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 491
Whz! 4ecs | ! mczn !e hzvc merc !hzn
enc rz|| s!zrk!
Wiih moic ihan onc call siacI, you gci ihc nen.nre ol having
muliilc ihings hacn ai ihc samc iimc. In icaliiy, only a iiuc
muliiioccssoi sysicm can aciually uo moic ihan onc ihing ai a
iimc, lui wiih ]ava ihicaus, ii can nen. ihai you`ic uoing scvcial
ihings simuliancously. In oihci woius, cxccuiion can movc lacI
anu loiih lciwccn siacIs so iaiuly ihai you lccl as ihough all siacIs
aic cxccuiing ai ihc samc iimc. Rcmcmlci, ]ava is |usi a ioccss
iunning on youi unucilying OS. So hisi, ]ava .eI has io lc ihc
cuiicnily cxccuiing ioccss` on ihc OS. Bui oncc ]ava gcis iis
iuin io cxccuic, cxacily wLn uocs ihc ]VM .ur. Which lyiccoucs
cxccuic. Whaicvci is on ihc io ol ihc cuiicnily-iunning siacI!
Anu in 100 milliscconus, ihc cuiicnily cxccuiing couc mighi swiich
io a J.e.er mcihou on a J.e.er siacI.
Onc ol ihc ihings a ihicau musi uo is Icc iiacI ol which siaicmcni
ol which mcihou) is cuiicnily cxccuiing on ihc ihicau`s siacI.
Ii mighi looI somcihing liIc ihis:
public static void main(String[] args) {
...
}
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
494 chapter 15
run{}
go{}
doMore{}
Ie mzkc z je| fer yeer !hrcz4,
|mp|cmcn! !hc Kennz||c |n!crfzrc
public class MyRunnable implements Runnable {
public void run() {
go();
}
public void go() {
doMore();
}
public void doMore() {
System.out.println(top o' the stack);
}
}
---.|- : - l- ..|.- .:.-,
:- ]-- --'l --- l- ---l l
---.|- .: --|] --- --l- l-
-|----l -|: - ---|` |-l --
.-----l:` 1: : ---- ]-- -l l-
)6B l- l--. : :--:- l- --- 1:
: l- --l- l.l --: .l l- -ll--
- l- --- :l.:
class ThreadTester {
public static void main (String[] args) {
Runnable threadJob = new MyRunnable();
Thread myThread = new Thread(threadJob);
myThread .start();
System.out.println(back in main);
}
}
|.:: l- --- ---.|- -:l.-:- -l- l- ---
1--. :--:l--:l-- 1: l-||: l- l--.
-.l --l- l- -l -- l- -ll-- - l- ---
:l.: |- -l-- ---:, l- -:l --l- l.l
l- --- l--. -|| ---
/-- ---'l -l . --- l--. - --:-l-- --l| ]--
:.|| :l.-l|` -- l- 1--. -:l.-:- A l--. :
--l --.||] . l--. --l| ]-- :l.-l l B---- l.l,
l': -:l . 1--. -:l.-:-, |- .-] -l-- --:l,
-l l ---'l .- .-] --.| 'l--.--::'
main thread
muin{}
myThreud,sturt{}
new thread
8f8l 88f00ll
What do you think the output will be if you run the
ThreadTester class? (we'll fnd out in a few pages)
RunnabIe interface
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 495
The three states of a new thread
A Thicau insiancc has lccn
cicaicu lui noi siaiicu.
In oihci woius, ihcic is a
Thicau ol|cci, lui no ihicau
ol cxccuiion.
NEW RUNNABLE
Thread t = new Thread(r);
Whcn you siaii ihc ihicau, ii
movcs inio ihc iunnallc siaic.
This mcans ihc ihicau is icauy
io iun anu |usi waiiing loi iis
Big Chancc io lc sclccicu loi
cxccuiion. Ai ihis oini, ihcic is
a ncw call siacI loi ihis ihicau.
t.start();
RUNNNG
t.start();
SeIecfed fo run
This is ihc siaic all ihicaus lusi
alici! To lc Thc Choscn Onc.
Thc Cuiicnily Running Thicau.
Only ihc ]VM ihicau schcuulci
can maIc ihai uccision. You
can somciimcs inuucncc ihai
uccision, lui you cannoi loicc a
ihicau io movc liom iunnallc
io iunning. In ihc iunning
siaic, a ihicau anu ONIY ihis
ihicau) has an aciivc call siacI,
anu ihc mcihou on ihc io ol
ihc siacI is cxccuiing.
Thread t = new Thread(r);
l: : ---- . l--.
-.-l: l- -'
But there's more. Once the thread becomes
runnable, it can move back and forth between
runnable, running, and an additional state:
temporarily not runnable {also known as blocked'}.
|'- -- l- - ''
c.- |
:---:--
l.l --
]--'
|'- -.l- l-
-l :l.-l-'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
496 chapter 15
RUNNABLE RUNNNG
SeIecfed fo run
Typical runnable/running loop
Senf bock fo runnobIe
so onofher fhreod con
hove o chonce
Tyically, a ihicau movcs lacI anu
loiih lciwccn iunnallc anu iunning,
as ihc ]VM ihicau schcuulci sclccis a
ihicau io iun anu ihcn IicIs ii lacI
oui so anoihci ihicau gcis a chancc.
A thread can be made
temporarily not-runnable
Thc ihicau schcuulci can movc a
iunning ihicau inio a llocIcu siaic,
loi a vaiiciy ol icasons. Ioi cxamlc,
ihc ihicau mighi lc cxccuiing couc
io icau liom a SocIci inui siicam,
lui ihcic isn`i any uaia io icau. Thc
schcuulci will movc ihc ihicau oui
ol ihc iunning siaic uniil somcihing
lccomcs availallc. Oi ihc cxccuiing
couc mighi havc iolu ihc ihicau io
ui iiscll io slcc slcc)). Oi ihc
ihicau mighi lc waiiing lccausc ii
iiicu io call a mcihou on an ol|cci,
anu ihai ol|cci was locIcu`. In ihai
casc, ihc ihicau can`i coniinuc uniil
ihc ol|cci`s locI is liccu ly ihc ihicau
ihai has ii.
All ol ihosc conuiiions anu moic)
causc a ihicau io lccomc icmoiaiily
noi-iunnallc.
RUNNABLE RUNNNG
BLOCKED
S
e
n
f
f
o
o
f
e
m
p
o
r
o
r
y
n
o
n
-
r
u
n
n
o
b
I
e
s
f
o
f
e
u
n
f
i
I
i
f
c
o
n
b
e
c
o
m
e
r
u
n
n
o
b
I
e
o
g
o
i
n
.
:|---, -.l- -- .--l-- l--. l- -:,
-.l- -- .l. l- - ..|.|- -- l- :l--.-,
-.l- -- .- --:l': |-:
thread states
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 497
Ihc Ihrcz4 8rhc4e|cr
Mumber four, you've hod
enough fime. 8ock fo runnobIe.
Mumber fwo, Iooks Iike you're upl
Oh, now if Iooks Iike you're gonno hove
fo sIeep. Mumber fve, come foke his
pIoce. Mumber fwo, you're sfiII
sIeeping...
[[ ([z]
,e[]a] z[, z]]
([ ]ej,jn, za(
w[ an, zn] w[
],n'(. q a,az]]y
z[, ([ ([z], (z[
(an,, nje]y. @a(
([', n gazzn(
za( ([z(. q jg[(
]( n ([z] an
( j(, [z(', en(n(
w[j] ([ ([
([z], ',(zv'.
Thc ihicau schcuulci maIcs all ihc uccisions aloui
who movcs liom iunnallc io iunning, anu aloui whcn
anu unuci whai ciicumsianccs) a ihicau lcavcs ihc
iunning siaic. Thc schcuulci ucciucs who iuns, anu loi
how long, anu whcic ihc ihicaus go whcn ihc schcuulci
ucciucs io IicI ihcm oui ol ihc cuiicnily-iunning siaic.
You can`i coniiol ihc schcuulci. Thcic is no API loi
calling mcihous on ihc schcuulci. Mosi imoiianily,
ihcic aic no guaianiccs aloui schcuuling! Thcic aic a
lcw nIo-guaianiccs, lui cvcn ihosc aic a liiilc luzzy.)
Thc loiiom linc is ihis: do not bose your progrom`s
correctness on the scheduIer worhing in o porticuIor woy:
Thc schcuulci imlcmcniaiions aic uillcicni loi
uillcicni ]VM`s, anu cvcn iunning ihc samc iogiam
on ihc samc machinc can givc you uillcicni icsulis.
Onc ol ihc woisi misiaIcs ncw ]ava iogiammcis
maIc is io icsi ihcii mulii-ihicaucu iogiam on a
singlc machinc, anu assumc ihc ihicau schcuulci will
always woiI ihai way, icgaiulcss ol whcic ihc iogiam
iuns.
So whai uocs ihis mcan loi wiiic-oncc-iun-anywhcic.
Ii mcans ihai io wiiic lailoim-inuccnucni ]ava couc,
youi mulii-ihicaucu iogiam musi woiI no maiici Low
ihc ihicau schcuulci lchavcs. Thai mcans ihai you can`i
lc uccnucni on, loi cxamlc, ihc schcuulci maIing
suic all ihc ihicaus iaIc nicc, cilccily laii anu cqual
iuins ai ihc iunning siaic. Alihough highly unliIcly
iouay, youi iogiam mighi cnu u iunning on a ]VM
wiih a schcuulci ihai says, OK ihicau hvc, you`ic u,
anu as lai as I`m conccincu, you can siay hcic uniil
you`ic uonc, whcn youi iun) mcihou comlcics."
Thc sccici io almosi cvciyihing is Iee. Thai`s
iighi, Iee. Puiiing a ihicau io slcc, cvcn loi a lcw
milliscconus, loiccs ihc cuiicnily-iunning ihicau io
lcavc ihc iunning siaic, ihus giving anoihci ihicau a
chancc io iun. Thc ihicau`s slcc) mcihou uocs comc
wiih ore guaianicc: a slccing ihicau will ro lccomc
ihc cuiicnily-iunning ihicau lcloic ihc ihc lcngih ol
iis slcc iimc has cxiicu. Ioi cxamlc, il you icll youi
ihicau io slcc loi iwo scconus 2,000 milliscconus),
ihai ihicau can ncvci lccomc ihc iunning ihicau again
uniil somciimc ne. ihc iwo scconus havc asscu.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
498 chapter 15
public class MyRunnable implements Runnable {
public void run() {
go();
}
public void go() {
doMore();
}
public void doMore() {
System.out.println(top o' the stack);
}
}
class ThreadTestDrive {
public static void main (String[] args) {
Runnable threadJob = new MyRunnable();
Thread myThread = new Thread(threadJob);
myThread.start();
System.out.println(back in main);
}
}
An example of how unpredictable the
scheduler can be...
Running this code on one machine: Produced this output:
File Edit Window Help PickMe
% java ThreadTestDrive
back in main
top o' the stack
% java ThreadTestDrive
top o' the stack
back in main
% java ThreadTestDrive
top o' the stack
back in main
% java ThreadTestDrive
top o' the stack
back in main
% java ThreadTestDrive
top o' the stack
back in main
% java ThreadTestDrive
top o' the stack
back in main
% java ThreadTestDrive
back in main
top o' the stack
N-l:- -- l- ---- :.--:
-.---|] ---l--: l- --- l--.
-:-: -:l, .- :---l--: l- -.-
l--. -:-: -:l
thread scheduIing
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 499
run{}
go{}
doMore{}
main thread
muin{}
myThreud,sturt{}
new thread
muin{}
myThreud,sturt{}
main thread
muin{}
ra|r() slarls l|e
reW l|read
T|e sc|edu|er serds
l|e ra|r l|read oul
ol rurr|r ard oac|
lo rurrao|e, so l|al
l|e reW l|read car
rur.
T|e sc|edu|er |els
l|e reW l|read
rur lo corp|el|or,
pr|rl|r oul 'lop o'
l|e slac|
T|e reW l|read oes
aWay, oecause |ls rur()
corp|eled. T|e ra|r
l|read orce aa|r
oecores l|e rurr|r
l|read, ard pr|rls 'oac|
|r ra|r
main thread
main thread
muin{}
myThreud,sturt{}
new thread
muin{}
myThreud,sturt{}
main thread
muin{}
ra|r() slarls l|e
reW l|read
T|e sc|edu|er serds
l|e ra|r l|read oul
ol rurr|r ard oac|
lo rurrao|e, so l|al
l|e reW l|read car
rur.
T|e sc|edu|er |els l|e
reW l|read rur lor a
||ll|e W|||e, rol |or
erou| lor l|e rur()
rel|od lo corp|ele.
main thread
run{}
go{}
run{}
go{}
new thread
T|e sc|edu|er
serds l|e reW
l|read oac| lo
rurrao|e.
T|e sc|edu|er
se|ecls l|e ra|r
l|read lo oe l|e
rurr|r l|read
aa|r. Va|r pr|rls
oul 'oac| |r ra|r
run{}
go{}
doMore{}
new thread
T|e reW l|read relurrs
lo l|e rurr|r slale
ard pr|rls oul 'lop o'
l|e slac|.
How did we end up with different results?
8ometimes it runs like this:
And sometimes it runs like this:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
socket connections
500 chapter 15
8ll P0lk5
A l|read W|l| a |oWer-case 'l' |s a separale l|read ol
execul|or |r Java.
Every l|read |r Java |as |ls oWr ca|| slac|.
A T|read W|l| a cap|la| 'T' |s l|e java.|ar.T|read
c|ass. A T|read oojecl represerls a l|read ol
execul|or.
A T|read reeds a joo lo do. A T|read's joo |s ar
|rslarce ol sorel||r l|al |rp|ererls l|e Rurrao|e
|rlerlace.
T|e Rurrao|e |rlerlace |as jusl a s|r|e rel|od, rur().
T||s |s l|e rel|od l|al oes or l|e oollor ol l|e reW
ca|| slac|. lr ol|er Words, |l |s l|e l|rsl rel|od lo rur |r
l|e reW l|read.
To |aurc| a reW l|read, you reed a Rurrao|e lo pass
lo l|e T|read's corslruclor.
A l|read |s |r l|e NEw slale W|er you |ave
|rslarl|aled a T|read oojecl oul |ave rol yel ca||ed
slarl().
w|er you slarl a l|read (oy ca|||r l|e T|read oojecl's
slarl() rel|od), a reW slac| |s crealed, W|l| l|e
Rurrao|e's rur() rel|od or l|e oollor ol l|e slac|.
T|e l|read |s roW |r l|e RuNNA8LE slale, Wa|l|r lo
oe c|oser lo rur.
A l|read |s sa|d lo oe RuNNlN0 W|er l|e JvV's
l|read sc|edu|er |as se|ecled |l lo oe l|e currerl|y-
rurr|r l|read. 0r a s|r|e-processor rac||re, l|ere
car oe or|y ore currerl|y-rurr|r l|read.
3orel|res a l|read car oe roved lror l|e RuNNlN0
slale lo a 8L0CKE0 (lerporar||y ror-rurrao|e) slale.
A l|read r||l oe o|oc|ed oecause |l's Wa|l|r lor dala
lror a slrear, or oecause |l |as ore lo s|eep, or
oecause |l |s Wa|l|r lor ar oojecl's |oc|.
T|read sc|edu||r |s rol uararleed lo Wor| |r ary
parl|cu|ar Way, so you carrol oe cerla|r l|al l|reads
W||| la|e lurrs r|ce|y. You car |e|p |rl|uerce lurr-la||r
oy pull|r your l|reads lo s|eep per|od|ca||y.
(-,- a,- |
oa|| qa--(:|-
I've seen exampIes that don't use a separate
RunnabIe impIementation, but instead just make a
subcIass of 7hread and override the 7hread's run()
method. 7hat way, you caII the 7hread's no-arg
constructor when you make the new thread,
7hread t = new 7hread(), // no RunnabIe
es, that |s another way of making your own
thread, but think about it from an OO perspective.
what's the purpose of subclassingI Pemember that
we're talking about two different things herethe
7hteoJ and the thread's joo. Prom an OO view, those
two are very separate activities, and belong in separate
classes. The only time you want to subclass/extend
the Thread class, is if you are making a new and more
specific type of Thread. |n other words, if you think of
the Thread as the worker, don't extend the Thread class
unless you need more specific wotlet behaviors. 8ut if
all you need is a new joo to be run by a Thread/worker,
then implement Punnable in a separate, joo-specific
(not wotlet-specific) class.
This is a design issue and not a performance or
language issue. |t's perfectly legal to subclass Thread
and override the run() method, but it's rarely a good
idea.
Can you reuse a 7hread object! Can you give it
a new job to do and then restart it by caIIing start()
again!
No. Once a thread's run() method has completed,
the thread can never be restarted. |n fact, at that
point the thread moves into a state we haven't talked
about. |n the dead state, the thread has
finished its run() method and can never be restarted.
The Thread ob|ect might still be on the heap, as a
living ob|ect that you can call other methods on (if
appropriate), but the Thread ob|ect has permanently
lost its 'threadness'. |n other words, there is no longer a
separate call stack, and the Thread ob|ect is no longer
a thteoJ. |t's |ust an ob|ect, at that point, like all other
ob|ects.
8ut, there are design patterns for making a pool of
threads that you can keep using to perform different
|obs. 8ut you don't do it by restarting() a dead thread.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 501
|e!!|n] z !hrcz4 !e s|ccp
Onc ol ihc lcsi ways io hcl youi ihicaus iaIc iuins is
io ui ihcm io slcc ciiouically. All you nccu io uo
is call ihc siaiic slcc) mcihou, assing ii ihc slcc
uuiaiion, in milliscconus.
Ioi cxamlc:
Thread.sleep(2000);
will InocI a ihicau oui ol ihc iunning siaic, anu
Icc ii oui ol ihc iunnallc siaic loi iwo scconus.
Thc ihicau nr` lccomc ihc iunning ihicau
again uniil alici ai lcasi iwo scconus havc asscu.
A lii unloiiunaicly, ihc slcc mcihou ihiows an
IniciiuicuExcciion, a chccIcu cxcciion, so all
calls io slcc musi lc wiacu in a iiy/caich oi
ucclaicu). So a slcc call ically looIs liIc ihis:
try {
Thread.sleep(2000);
} catch(InterruptedException ex) {
ex.printStackTrace();
}
Youi ihicau will iolally re.e. lc iniciiuicu liom
slcc, ihc cxcciion is in ihc API io suoii a ihicau
communicaiion mcchanism ihai almosi nolouy uscs in
ihc Rcal Woilu. Bui, you siill havc io olcy ihc hanulc
oi ucclaic law, so you nccu io gci uscu io wiaing youi
slcc) calls in a iiy/caich.
Now you Inow ihai youi ihicau won`i waIc u beo.e ihc
sccihcu uuiaiion, lui is ii ossillc ihai ii will waIc u
somc iimc ne. ihc iimci` has cxiicu. Ycs anu no. Ii
uocsn`i maiici, ically, lccausc whcn ihc ihicau waIcs
u, it oIwoys goes boch to the runnobIe stote: Thc ihicau
won`i auiomaiically waIc u ai ihc ucsignaicu iimc anu
lccomc ihc cuiicnily-iunning ihicau. Whcn a ihicau
waIcs u, ihc ihicau is oncc again ai ihc mcicy ol
ihc ihicau schcuulci. Now, loi alicaiions ihai uon`i
icquiic cilcci iiming, anu ihai havc only a lcw ihicaus,
ii mighi acai as ihough ihc ihicau waIcs u anu
icsumcs iunning iighi on schcuulc say, alici ihc 2000
milliscconus). Bui uon`i lci youi iogiam on ii.
]a( ya ([z] ( ,]
j| ya wzn( ( ,a
([z( ([ ([z], g( z
e[zne ( an.
y[n ([ ([z] wz[,
a, j( z]wzy, g, ze[
( ([ annz] ,(z(
zn] wzj(, | ([ ([z]
,e[]a] ( e[, j(
( an zgzjn.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
502 chapter 15
0s|n] s|ccp !e mzkc eer pre]rzm
merc prc4|r!z||c.
Rcmcmlci oui cailici cxamlc ihai Ici giving us uillcicni
icsulis cach iimc wc ian ii. IooI lacI anu siuuy ihc couc
anu ihc samlc ouiui. Somciimcs main hau io waii uniil ihc
ncw ihicau hnishcu anu iinicu io o` ihc siacI"), whilc
oihci iimcs ihc ncw ihicau woulu lc scni lacI io iunnallc
lcloic ii was hnishcu, allowing ihc main ihicau io comc lacI
in anu iini oui lacI in main". How can wc hx ihai. Sio
loi a momcni anu answci ihis qucsiion: Whcic can you ui
a slcc) call, io maIc suic ihai lacI in main" always iinis
lcloic io o` ihc siacI".
Wc`ll waii whilc you woiI oui an answci ihcic`s moic ihan
onc answci ihai woulu woiI).
Iiguic ii oui.
public class MyRunnable implements Runnable {
public void run() {
go();
}
public void go() {
try {
Thread.sleep(2000);
} catch(InterruptedException ex) {
ex.printStackTrace();
}
doMore();
}
public void doMore() {
System.out.println(top o' the stack);
}
}
class ThreadTestDrive {
public static void main (String[] args) {
Runnable theJob = new MyRunnable();
Thread t = new Thread(theJob);
t.start();
System.out.println(back in main);
}
}
c.||- :|-- --- -|| --:- l- ---
l--. l- |-.- l- :-----l|]~-----
:l.l-'
1- -.- l--. -|| -:--- l-
:-----l|]~----- l--. ..-, .- --l
--l .: - -.-' 1-- l--- -|| - .
.-:- |-- .--l l-- :-:--:` ---- --
-l l- l: |--, -: :.||: -M---|` .-
--l: --l l- -' l- :l.:'
File Edit Window Help SnoozeButton
% java ThreadTestDrive
back in main
top o' the stack
% java ThreadTestDrive
back in main
top o' the stack
% java ThreadTestDrive
back in main
top o' the stack
% java ThreadTestDrive
back in main
top o' the stack
% java ThreadTestDrive
back in main
top o' the stack
1: : -.l -- -.-l-. :--::l--l ----
- --l :l.l----l:
using Thread.sIeep()
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 503
Mzk|n] zn4 s!zr!|n] ! we !hrcz4s
Thicaus havc namcs. You can givc youi ihicaus a namc ol
youi choosing, oi you can accci ihcii uclauli namcs. Bui ihc
cool ihing aloui namcs is ihai you can usc ihcm io icll which
ihicau is iunning. Thc lollowing cxamlc siaiis iwo ihicaus.
Each ihicau has ihc samc |ol: iun in a loo, iiniing ihc
cuiicnily-iunning ihicau`s namc wiih cach iiciaiion.
public class RunThreads implements Runnable {
public static void main(String[] args) {
RunThreads runner = new RunThreads();
Thread alpha = new Thread(runner);
Thread beta = new Thread(runner);
alpha.setName(Alpha thread);
beta.setName(Beta thread);
alpha.start();
beta.start();
}
public void run() {
for (int i = 0; i < 25; i++) {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + is running);
}
}
}
M
.- --- ---.|- -:l.-:-
M.- l-- l--.:, -l l- :.-- ---.|- |l-
:.-- -~~--'|| l.| ---- .--l l- l-- l--.:
.- --- ---.|-' - . -- .-:`
N.-- l- l--.:
l.-l l- l--.:
!.: l--. -|| --- l--- l: |--,
--l- l: -.-- -.: l--
Whz! w||| hzppcn!
Will ihc ihicaus iaIc iuins. Will you scc ihc ihicau namcs
alicinaiing. How olicn will ihcy swiich. Wiih cach iiciaiion.
Alici hvc iiciaiions.
You alicauy Inow ihc answci: we Jor` Irow Ii`s u io ihc
schcuulci. Anu on youi OS, wiih youi aiiiculai ]VM, on
youi CPU, you mighi gci vciy uillcicni icsulis.
Running unuci OS X 10.2 ]aguai), wiih hvc oi lcwci
iiciaiions, ihc Alha ihicau iuns io comlciion, ihcn
ihc Bcia ihicau iuns io comlciion. Vciy consisicni. Noi
guaianiccu, lui vciy consisicni.
Bui whcn you u ihc loo io 2 oi moic iiciaiions, ihings
siaii io wolllc. Thc Alha ihicau mighi noi gci io comlcic
all 2 iiciaiions lcloic ihc schcuulci scnus ii lacI io
iunnallc io lci ihc Bcia ihicau havc a chancc.
File Edit Window Help Centauri
Alpha thread is running
Alpha thread is running
Alpha thread is running
Beta thread is running
Alpha thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Beta thread is running
Alpha thread is running
|.-l - l- --l-l ---
l- |-- l--.l-: i-
l--:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
504 chapter 15
0m, ycs. Ihcrc |8 z 4zrk s|4c.
Ihrcz4s rzn |cz4 !e renrerrcnry '|ssecs.
Concuiicncy issucs lcau io iacc conuiiions. Racc conuiiions
lcau io uaia coiiuiion. Daia coiiuiion lcaus io lcai... you
Inow ihc icsi.
Ii all comcs uown io onc oicniially ucauly sccnaiio: iwo oi
moic ihicaus havc acccss io a singlc ol|cci`s . In oihci
woius, mcihous cxccuiing on iwo uillcicni siacIs aic loih
calling, say, gciicis oi sciicis on a singlc ol|cci on ihc hca.
Ii`s a wholc lcli-hanu-uocsn`i-Inow-whai-ihc-iighi-hanu-
is-uoing` ihing. Two ihicaus, wiihoui a caic in ihc woilu,
humming along cxccuiing ihcii mcihous, cach ihicau
ihinIing ihai hc is ihc Onc Tiuc Thicau. Thc only onc
ihai maiicis. Alici all, whcn a ihicau is noi iunning, anu in
iunnallc oi llocIcu) ii`s csscniially InocIcu unconscious.
Whcn ii lccomcs ihc cuiicnily-iunning ihicau again, ii uocsn`i
Inow ihai ii cvci siocu.
Wowl Threods ore
fhe greofesf fhing since fhe
MIMI Cooperl I con'f fhink
of o singIe downside fo using
fhreods, con you7
aren't threads wonderfuI?
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 505
Marriage in TroubIe.
Can this coupIe be saved?
Next, on a very special Dr.Steve Show
[Transcript from episode #42]
WeIcome Lo LLe Dr. BLeve sLow.
We've oL a sLory Loday LLaL's cenLered around LLe Lop Lwo reasons wLy
coupIes spIIL up-Bnances and sIeep.
Today's LroubIed paIr, Fyan and MonIca, sLare a bed and a
bank accounL. EuL noL Ior Ion II we can'L Bnd a soIuLIon. TLe
probIem? TLe cIassIc "Lwo peopIe-one bank accounL" LLIn.
Here's Low MonIca descrIbed IL Lo me:
"Fyan and I areed LLaL neILLer oI us wIII overdraw LLe cLeckIn accounL.
Bo LLe procedure Is, wLoever wanLs Lo wILLdraw money musL cLeck LLe
baIance In LLe accounL beIore makIn LLe wILLdrawaI. IL aII seemed so
sImpIe. EuL suddenIy we're bouncIn cLecks and eLLIn LIL wILL overdraIL
Iees!
I LLouLL IL wasn'L possIbIe, I LLouLL our procedure was saIe. EuL LLen
LLIs Lappened:
Fyan needed $S0, so Le cLecked LLe baIance In LLe accounL,
and saw LLaL IL was $100. No probIem. Bo, Le pIans Lo
wILLdraw LLe money. But Brst he taIIs asIeep!
And LLaL's wLere I come In, wLIIe Fyan's sLIII asIeep, and
now I wanL Lo wILLdraw $100. I cLeck LLe baIance, and
IL's $100 (because Fyan's sLIII asIeep and Lasn'L yeL made
LIs wILLdrawaI}, so I LLInk, no probIem. Bo I make LLe
wILLdrawaI, and aaIn no probIem. EuL LLen Fyan wakes up,
compIeLes LIs wILLdrawaI, and we're suddenIy overdrawn! He dIdn'L
even know LLaL Le IeII asIeep, so Le jusL wenL aLead and compIeLed LIs
LransacLIon wILLouL cLeckIn LLe baIance aaIn. You've oL Lo LeIp us Dr.
BLeve!"
Is LLere a soIuLIon? Are LLey doomed? We can'L sLop Fyan Irom IaIIIn
asIeep, buL can we make sure LLaL MonIca can'L eL Ler Lands on LLe bank
accounL unLII aILer Le wakes up?
Take a momenL and LLInk abouL LLaL wLIIe we o Lo a commercIaI break.
].- .||: .:|-- .l--
- :-:: l- .|.-:-
-l ---- - -.-: l-
-l-.-.| w-- - -.-:
-, - ---.l-|] -.-:
l- -l-.-| -l--l
:-:- l- .|.-:- ..-
].- .- M--:. :l-:
- l- l-- --|-, ---
.::---l' --|--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
506 chapter 15
Ihc Kyzn zn4 Men|rz pre||cm, |n re4c
Thc lollowing cxamlc shows whai can hacn whcn wo
ihicaus Ryan anu Monica) shaic a .rIe ol|cci ihc lanI
accouni).
Thc couc has iwo classcs, BanIAccouni, anu
MonicaAnuRyan]ol. Thc MonicaAnuRyan]ol class
imlcmcnis Runnallc, anu icicscnis ihc lchavioi ihai Ryan
anu Monica loih havc-chccIing ihc lalancc anu maIing
wiihuiawals. Bui ol couisc, cach ihicau lalls aslcc .r beweer
chccIing ihc lalancc anu aciually maIing ihc wiihuiawal.
Thc MonicaAnuRyan]ol class has an insiancc vaiiallc ol iyc
BanIAccouni., ihai icicscnis ihcii shaicu accouni.
Thc couc woiIs liIc ihis:
1 Muke one instunce of PyunAndMonicuJob,
The PyonAndMonicoJob cIoss is fhe PunnobIe (fhe job fo do),
ond since bofh Monico ond Pyon do fhe some fhing (check
boIonce ond wifhdrow money), we need onIy one insfonce.
ankAccount
|rl oa|arce
el8a|arce()
W|l|draW()
RyanAndHon|caJob
8ar|Accourl accourl
rur()
ra|ew|l|draWa|()
-:''
We lost the last updates
that Thread A madel
Thread B had previously
done a read' of the value
of balance, and when B
woke up, it ]ust kept going
as if it never missed a beat.
1--. A -.l- l l- -, -l
--- B :.-- .: .- :l--
-- l- - l- -.l- A -.-,
.: A': -.l- ---- .---
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
514 chapter 15
Mzkc !hc |nrrcmcn!|I mc!he4 z!em|r.
8ynrhren|zc | !|
Synchionizing ihc incicmcni) mcihou solvcs ihc Iosi
Uuaic" iollcm, lccausc ii Iccs ihc iwo sics in ihc mcihou
as onc unlicaIallc unii.
public synchronized void increment() {
int i = balance;
balance = i + 1;
}
Once a thread enters
the method, we have
to make sure that all
the steps in the method
complete {as one
atomic process} before
any other thread can
enter the method.
B
(-,- a,- |
oa|| qa--(:|-
Sounds Iike it's a good idea to synchronize
everything, just to be thread-safe.
Nope, it's not a good idea. Synchronization doesn't
come for free. Pirst, a synchronized method has a certain
amount of overhead. |n other words, when code hits a
synchronized method, there's going to be a performance hit
(although typically, you'd never notice it) while the matter of
"is the key availableI is resolved.
Second, a synchronized method can slow your program
down because synchronization restricts concurrency. |n
other words, a synchronized method forces other threads to
get in line and wait their turn. This might not be a problem
in your code, but you have to consider it.
Third, and most frightening, synchronized methods can lead
to deadlock! (See page 5l6.)
A good rule of thumb is to synchronize only the bare
minimum that should be synchronized. And in fact, you
can synchronize at a granularity that's even smaller than
a method. we don't use it in the book, but you can use the
synchronized keyword to synchronize at the more fine-
grained level of one or more statements, rather than at the
whole-method level.
-l-|` --:-'l --- l-
- :]-:-----, :- -- --'l
:]-:----- l- --|- --l-
N--, --|] l-:- l-- --l- :.||: .-- ----
-l- --- .l--: --l w-- ]-- -:- l- :]-:----- -]--- w|1+|N . --l-,
-.l-- l.- - . --l- -:|.-.l--, ]--
.- l- --- .- .-----l l.l : l-
--:l --:- -] l- l--. ---: l- -l
A|l-- l--- .-- -l-- -.]: l- - l, ]--
-|| .|--:l .|-.]: :]-:----- -- l- :-----l
--:l |l:` 1.l': l- :.-- --:l ]--'
|-: l- --|- --l- ---- :]-:-----
public void go() {
doStuff();
synchronized(this) {
criticalStuff();
moreCriticalStuff();
}
}
synchronizing methods
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 515
CaJe Kagaets
class ThreadOne
class Accum {
class ThreadTwo
public class TestThreads {
onus uestion: why do you think we used the
modifiers we did in the Accum classI
exercise: Code Magnets
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 525
try {
Thread.sleep{50|,
Thread.sleep{50|,
CaJe Kagaets, :aatiaaeJ..
counter += add,
return a,
implements Runnable {
public void run{| {
return counter,
one.start{|,
a.updateCounter{l000|,
Thread one = new Thread{tl|,
try {
public static void main{String args| {
for{int x=0, x < 99, x++| {
} catch{InterruptedException ex| { }
private static Accum a = new Accum{|,
} catch{InterruptedException ex| { }
implements Runnable {
Accum a = Accum.getAccum{|,
Accum a = Accum.getAccum{|,
public void run{| {
for{int x=0, x < 98, x++| {
two.start{|,
ThreadOne tl = new ThreadOne{|,
ThreadTwo t2 = new ThreadTwo{|,
public void updateCounter{int add| {
private Accum{| { }
public int getCount{| {
System.out.println{"two "+a.getCount{||,
System.out.println{"one "+a.getCount{||,
public static Accum getAccum{| {
private int counter = 0,
a.updateCounter{l|,
Thread two = new Thread{t2|,
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
526 chapter 15
]e;ejze o|ajoz
public class TestThreads {
public static void main{String args| {
ThreadOne tl = new ThreadOne{|,
ThreadTwo t2 = new ThreadTwo{|,
Thread one = new Thread{tl|,
Thread two = new Thread{t2|,
one.start{|,
two.start{|,
}
}
class Accum {
private static Accum a = new Accum{|,
private int counter = 0,
private Accum{| { }
public static Accum getAccum{| {
return a,
}
public void updateCounter{int add| {
counter += add,
}
public int getCount{| {
return counter,
}
}
class ThreadOne implements Runnable {
Accum a = Accum.getAccum{|,
public void run{| {
for{int x=0, x < 98, x++| {
a.updateCounter{l000|,
try {
Thread.sleep{50|,
} catch{InterruptedException ex| { }
}
System.out.println{"one "+a.getCount{||,
}
}
class ThreadTwo implements Runnable {
Accum a = Accum.getAccum{|,
public void run{| {
for{int x=0, x < 99, x++| {
a.updateCounter{l|,
try {
Thread.sleep{50|,
} catch{InterruptedException ex| { }
}
System.out.println{"two "+a.getCount{||,
}
}
Threods from fwo differenf cIosses ore updofing
fhe some objecf in o fhird cIoss, becouse bofh
fhreods ore occessing o singIe insfonce of Accum.
The Iine of code:
private static Accum a new Accum( ), creofes o
sfofic insfonce of Accum (remember sfofic meons
one per cIoss), ond fhe privofe consfrucfor in
Accum meons fhof no one eIse con moke on Accum
objecf. These fwo fechniques (privofe consfrucfor
ond sfofic geffer mefhod) used fogefher, creofe
whof's known os o 'SingIefon' - on OO poffern fo
resfricf fhe number of insfonces of on objecf
fhof con exisf in on oppIicofion. (UsuoIIy, fhere's
jusf o singIe insfonce of o SingIefon-hence fhe
nome), buf you con use fhe poffern fo resfricf fhe
insfonce creofion in whofever woy you choose.)
:--.l- . :l.l: -:l.-:-
- :|.:: A::--
A -.l- :--:l--:l--
exercise soIutions
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
networking and threads
you are here 527
As Sarah joined the on-board development team`s design review meeting , she gazed out
the portal at sunrise over the Indian Ocean. Even though the ship`s conIerence room was
incredibly claustrophobic, the sight oI the growing blue and white crescent overtaking night on
the planet below flled Sarah with awe and appreciation.
This morning`s meeting was Iocused on the control systems Ior the orbiter`s airlocks.
As the fnal construction phases were nearing their end, the number oI spacewalks was
scheduled to increase dramatically, and traIfc was high both in and out oI the ship`s
airlocks. 'Good morning Sarah, said Tom, 'Your timing is perIect, we`re just starting
the detailed design review.
'As you all know, said Tom, 'Each airlock is outftted with space-hardened GUI
terminals, both inside and out. Whenever spacewalkers are entering or exiting the orbiter
they will use these terminals to initiate the airlock sequences. Sarah nodded, 'Tom can
you tell us what the method sequences are Ior entry and exit? Tom rose, and foated to the
whiteboard, 'First, here`s the exit sequence method`s pseudocode, Tom quickly wrote on the
board.
orbiterAirlockExitSequence()
verifyPortalStatus();
pressurizeAirlock();
openInnerHatch();
conhrmAirlockOccupied();
closeInnerHatch();
decompressAirlock();
openOuterHatch();
conhrmAirlockVacated();
closeOuterHatch();
'To ensure that the sequence is not interrupted, we have synchronized all oI the
methods called by the orbiterAirlockExitSequence() method, Tom explained. 'We`d hate to
see a returning spacewalker inadvertently catch a buddy with his space pants down!
Everyone chuckled as Tom erased the whiteboard, but something didn`t Ieel right
to Sarah and it fnally clicked as Tom began to write the entry sequence pseudocode on the
whiteboard. 'Wait a minute Tom!, cried Sarah, 'I think we`ve got a big faw in the exit
sequence design, let`s go back and revisit it, it could be critical!
Why aia Sarah stop the meeting? What aia she suspect?
]Jc_Jna[c
_s[ci
Near-miss at the Airlock
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
528 chapter 15
What did Sarah knov?
Saiah icalizcu ihai in oiuci io cnsuic ihai ihc cniiic cxii
scqucncc woulu iun wiihoui iniciiuiion ihc
orbiterAirlockExitSequence ) mcihou nccucu io
lc synchionizcu. As ihc ucsign sioou, ii woulu lc ossillc
loi a iciuining saccwalIci io iniciiui ihc Exii Scqucncc!
Thc Exii Scqucncc ihicau coulun`i lc iniciiuicu in ihc
miuulc ol any ol ihc lowci lcvcl mcihou calls, lui ii ouIJ lc
iniciiuicu in beweer ihosc calls. Saiah Incw ihai ihc cniiic
scqucncc shoulu lc iun as onc aiomic unii, anu il ihc orbit
erAirlockExitSequence( ) mcihou was synchionizcu, ii
coulu noi lc iniciiuicu ai any oini.
puzzIe answers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
this is a new chapter 529
Sorting is a snap in Java. ou have all the tools for collecting and manipulating
your data without having to write your own sort algorithms (unless you're reading this right
now sitting in your Computer Science l0l class, in which case, trust usyou are SO going to be
writing sort code while the rest of us |ust call a method in the 1ava AP|). The 1ava Collections
Pramework has a data structure that should work for virtually anything you'll ever need to do.
want to keep a list that you can easily keep adding toI want to find something by nameI want
to create a list that automatically takes out all the duplicatesI Sort your co-workers by the
number of times they've stabbed you in the backI Sort your pets by number of tricks learnedI
|t's all here...
Tree8et
Keeps l|e e|ererls sorled ard preverls dup||cales.
hashHap
Lel's you slore ard access e|ererls as rare/va|ue pa|rs.
L|nkedL|st
0es|red lo |ve oeller perlorrarce W|er you |rserl or de|ele
e|ererls lror l|e r|dd|e ol l|e co||ecl|or. (lr pracl|ce, ar
ArrayL|sl |s sl||| usua||y W|al you Warl.)
hash8et
Preverls dup||cales |r l|e co||ecl|or, ard |ver ar e|ererl, car
l|rd l|al e|ererl |r l|e co||ecl|or qu|c||y.
L|nkedhashHap
L||e a reu|ar las|Vap, excepl |l car rereroer l|e order |r
W||c| e|ererls (rare/va|ue pa|rs) Were |rserled, or |l car oe
corl|ured lo rereroer l|e order |r W||c| e|ererls Were |asl
accessed.
l--'l ----] .--l l-]-
l- |-.-- l-:- -l-- ---:
-l --- w-'|| - -l-
---- -l.|: . |ll|- |.l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
534 chapter 16
Il you ui all ihc Siiings ihc song iiilcs) inio a insicau ol
an AiiayIisi, ihc Siiings woulu auiomaiically lanu in ihc iighi lacc,
alhalciically soiicu. Whcncvci you iinicu ihc lisi, ihc clcmcnis woulu
always comc oui in alhalciical oiuci.
Anu ihai`s gicai whcn you nccu a wc`ll
ialI aloui scis in a lcw minuics) oi whcn
you Inow ihai ihc lisi musi siay
soiicu alhalciically.
On ihc oihci hanu, il you uon`i nccu ihc
lisi io siay soiicu, TiccSci mighi lc moic
cxcnsivc ihan you nccu-every time you
insert into o TreeSet, the TreeSet hos to tohe
the time to fgure out where in the tree the new
eIement must go. Wiih AiiayIisi, insciis can
lc llinuingly lasi lccausc ihc ncw clcmcni
|usi gocs in ai ihc cnu.
Yee ree|4 esc z Ircc8c!...
0r yee ree|4 esc !hc 0e||cr!|ens.ser!|I mc!he4
CoIIections.sort()
puo||c slal|c vo|d copy(L|sl desl|ral|or, L|sl source)
puo||c slal|c L|sl emptyL|st()
puo||c slal|c vo|d f|||(L|sl ||slToF|||, 0ojecl oojToF|||llw|l|)
puo||c slal|c |rl frequency(Co||ecl|or c, 0ojecl o)
puo||c slal|c vo|d reverse(L|sl ||sl)
puo||c slal|c vo|d rotate(L|sl ||sl, |rl d|slarce)
puo||c slal|c vo|d shuff|e(L|sl ||sl)
puo||c slal|c vo|d sort(L|sl ||sl)
puo||c slal|c ooo|ear rep|aceA||(L|sl ||sl, 0ojecl o|dva|, 0ojecl reWva|)
// rary rore rel|ods...
java.ut||.6o||ect|ons
Is "" the onIy thing you can put there! ecause the docs for sort used "7"....
ou can use anything that's a legal 1ava identifier. That means anything that you
could use for a method or variable name will work as a type parameter. 8ut the conven-
tion is to use a single letter (so that's what you should use), and a further convention is to
use "T unless you're specifically writing a collection class, where you'd use "L to repre-
sent the "type of the Llement the collection will hold.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
544 chapter 16
0s|n] ]cncr|r MIIH0P8
A gcnciic In mcans ihai ihc In JeIn.n.or incluucs a iyc
aiamcici. A gcnciic eLoJ mcans ihai ihc mcihou ucclaiaiion
uscs a iyc aiamcici in iis signaiuic.
You can usc iyc aiamcicis in a mcihou in scvcial uillcicni ways:
1 Us|ng a type parameter def|ned |n the c|ass dec|arat|on
Whcn you ucclaic a iyc aiamcici loi ihc class, you
can simly usc ihai iyc any lacc ihai you`u usc a
.enI class oi inicilacc iyc. Thc iyc ucclaicu in ihc
mcihou aigumcni is csscniially iclaccu wiih ihc iyc
you usc whcn you insianiiaic ihc class.
2 Us|ng a type parameter that was N0T def|ned |n the c|ass dec|arat|on
Il ihc class iiscll uocsn`i usc a iyc aiamcici, you can siill
sccily onc loi a mcihou, ly ucclaiing ii in a ically unusual
lui availallc) sacc-beo.e Le .eu.r ,e. This mcihou says
ihai T can lc any iyc ol Animal".
public boolean add(E o)
public class ArrayList<E> extends AbstractList<E> ... {
/-- :.- -:- l- !' --- 6N|/ -:.-:- l':
.|--.] --- --- .: .-l - l- :|.::
public <T extends Animal> void takeThing(ArrayList<T> list)
+--- -- :.- -:- 1 -:.-:- -- -:|.--
1' -.-|-- - l- --l- -:|.-.l--
generic methods
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 545
Woif... fhof con'f be righf. If you con
foke o Iisf of AnimoI, why don'f you
jusf SAY fhof7 Whof's wrong wifh jusf
tukeThing{ArruyList-AnimuI> Iist}7
Hcrcs whcrc | ! ]c!s wc|r4...
This:
public <T extends Animal> void takeThing(ArrayList<T> list)
Is NOT the some os this:
public void takeThing(ArrayList<Animal> list)
Boih aic lcgal, lui ihcy`ic J.e.er!
Thc hisi onc, whcic <T cxtcnds Animal> is aii ol ihc mcihou
ucclaiaiion, mcans ihai any AiiayIisi ucclaicu ol a iyc ihai is
Animal, oi onc ol Animal`s suliycs liIc Dog oi Cai), is lcgal.
So you coulu invoIc ihc io mcihou using an AiiayIisiDog>,
AiiayIisiCai>, oi AiiayIisiAnimal>.
Bui... ihc onc on ihc loiiom, whcic ihc mcihou aigumcni is
AiiayIisiAnimal> lisi) mcans ihai orI, an AiiayIisiAnimal>
is lcgal. In oihci woius, whilc ihc hisi vcision iaIcs an AiiayIisi
ol any iyc ihai is a iyc ol Animal Animal, Dog, Cai, cic.),
ihc scconu vcision iaIcs orI, an AiiayIisi ol iyc Animal. Noi
AiiayIisiDog>, oi AiiayIisiCai> lui only AiiayIisiAnimal>.
Anu ycs, ii uocs acai io violaic ihc oini ol olymoihism.
lui ii will lccomc clcai whcn wc icvisii ihis in uciail ai ihc cnu
ol ihc chaici. Ioi now, icmcmlci ihai wc`ic only looIing ai
ihis lccausc wc`ic siill iiying io hguic oui how io soii) ihai
SongIisi, anu ihai lcu us inio looIing ai ihc API loi ihc soii)
mcihou, which hau ihis siiangc gcnciic iyc ucclaiaiion.
For now, oII you need to hnow is thot the syntox o[ the top version
is IegoI, ond thot it meons you con poss in o ArroyList object
instontioted os AnimoI or ony AnimoI subtype.
Anu now lacI io oui soii) mcihou...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
546 chapter 16
import java.util.*;
import java.io.*;
public class Jukebox3 {
ArrayList<Song> songList = new ArrayList<Song>();
public static void main(String[] args) {
new Jukebox3().go();
}
public void go() {
getSongs();
System.out.println(songList);
Collections.sort(songList);
System.out.println(songList);
}
void getSongs() {
try {
File hle = new File(SongList.txt);
BufferedReader reader = new BufferedReader(new FileReader(hle));
String line = null;
while ((line= reader.readLine()) != null) {
addSong(line);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
void addSong(String lineToParse) {
String[] tokens = lineToParse.split(/);
Song nextSong = new Song(tokens[0], tokens[1], tokens[2], tokens[3]);
songList.add(nextSong);
}
}
This sfiII doesn'f
expIoin why fhe sorf mefhod
foiIed on on ArroyLisf of Songs
buf worked for on ArroyLisf of
Sfrings...
Remember where we were...
1: : ---- l --.:' |l ---- -- ---
.::- - .- A--.]|:ll--, -l .: :--- .: --
l-- l- :--l .- A--.]|:l--, l .|-
File Edit Window Help Bummer
%javac Jukebox3.java
Jukebox3.java:15: cannot nd symbol
symbol : method sort(java.util.ArrayList<Song>)
location: class java.util.Collections
Collections.sort(songList);
^
1 error
sorting a Song
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 547
public static <T extends Comparable<? super T>> void sort(List<T> list)
The sort{} method can take only lists
of Comparable ob]ects.
8ong is NOT a subtype of
Comparable, so you cannot sort{}
the list of 8ongs.
At least not yet...
1: :.]: w.l--- '1' : --:l
- - l]- c--.-.|-'
||---- l: .-l -- --- B-l
]-- :.-'l, l -:l --.-:
l.l l- l]- .-.--l-- --
c--.-.|- --:l - - l]- 1
-- --- - 1': :---l]-:`
/-- :.- .:: - --|] . |:l |--
:-l]- - |:l, |- A--.]|:l`
l.l -:-: . .-.--l---- l]-
l.l -l--: c--.-.|-'
So hcic wc aic, iiying io icau ihc soii) mcihou uocs io h nu
oui why ii was OK io soii a lisi ol Siiings, lui noi a
lisi ol Song ol|ccis. Anu ii looIs liIc ihc answci is...
Kcv|s| !|n] !hc ser!| I mc!he4
Um... I jusf checked fhe docs for
Sfring, ond Sfring doesn'f EXTEMD
ComporobIe--if IMPLEMEMTS if.
CompurubIe is un interfuce. So if's nonsense
fo soy T etends ComporobIe.
public nal class String extends Object implements Serializable,
Comparable<String>, CharSequence
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
548 chapter 16
Thc ]ava cnginccis hau io givc you a way io ui a consiiaini
on a aiamciciizcu iyc, so ihai you can icsiiici ii io, say, only
sulclasscs ol Animal. Bui you also nccu io consiiain a iyc io
allow only classcs ihai imlcmcni a aiiiculai inicilacc. So
hcic`s a siiuaiion whcic wc nccu onc Iinu ol syniax io woiI
loi loih siiuaiions-inhciiiancc anu imlcmcniaiion. In oihci
woius, ihai woiIs loi loih e:erJ anu .Ieer.
Anu ihc winning woiu was... e:erJ. Bui ii ically mcans is-a",
anu woiIs icgaiulcss ol whcihci ihc iyc on ihc iighi is an
inicilacc oi a class.
|n ]cncr|rs, cr!cn4s mczns
cr!cn4s er |mp|cmcn!s
public static <T extends Comparable<? super T>> void sort(List<T> list)
c--.-.|- : .- -l--.:-, :- l:
!A||/ --.:, 1 --:l - . l]- l.l
-|----l: l- c--.-.|- -l--.:-'
|l --:-'l -.ll-- --l-- l- l- -- l- -l :
. :|.:: -- -l--.:- ]-- :l|| :.] -l--:'
]n gnje,, ([ [yw]
y(n], z]]y zn, j,-z,
zn] w[, | @0[q e]z,,,
zn] jn(|ze,.
+,-+ :+ ,-+:.|
coIIections exercise
Note: answers are at the end of
the chapter.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 555
Por each of the questions below, fill in the blank
with one of the words from the "possible answers
list, to correctly answer the question. Answers are
at the end of the chapter.
Givcn ihc lollowing comilallc siaicmcni:
Collections.sort(myArrayList);
1. Whai musi ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni. ________________
2. Whai mcihou musi ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni. ________________
S. Can ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni loih
Comparator AND Comparable. ________________
Givcn ihc lollowing comilallc siaicmcni:
Collections.sort(myArrayList, myCompare);
4. Can ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni Comparable. ________________
. Can ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni Comparator. ________________
6. Musi ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni Comparable. ________________
7. Musi ihc class ol ihc ol|ccis sioicu in myArrayList imlcmcni Comparator. ________________
S. Whai musi ihc class ol ihc myCompare ol|cci imlcmcni. ________________
9. Whai mcihou musi ihc class ol ihc myCompare ol|cci imlcmcni. __________________
Possible Answers:
6omparator,
6omparab|e,
compareTo( },
compare( },
yes,
no
]j||-j-ge-|z
+,-+ :+ ,-+:.|
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
556 chapter 16
0h-eh. Ihc ser!|n] z|| werks, |e! new wc hzvc 4ep||rz!cs...
Thc soiiing woiIs gicai, now wc Inow how io soii on loih using ihc Song ol|cci`s
comaicTo) mcihou) anu using ihc Comaiaioi`s comaic) mcihou). Bui ihcic`s
a ncw iollcm wc uiun`i noiicc wiih a icsi samlc ol ihc |uIclox icxi hlc-the sorted Iist
contoins dupIicotes.
Ii acais ihai ihc uinci |uIclox |usi Iccs wiiiing io ihc hlc icgaiulcss ol whcihci ihc
samc song has alicauy lccn laycu anu ihus wiiiicn) io ihc icxi hlc. Thc SongIisiMoic.ixi
|uIclox icxi hlc is a comlcic iccoiu ol cvciy song ihai was laycu, anu mighi coniain ihc
samc song muliilc iimcs.
File Edit Window Help TooManyNotes
%java Jukebox4
[Pink Moon: Nick Drake, Somersault: Zero 7, Shiva Moon: Prem
Joshua, Circles: BT, Deep Channel: Afro Celts, Passenger:
Headmix, Listen: Tahiti 80, Listen: Tahiti 80, Listen: Tahiti
80, Circles: BT]
[Circles: BT, Circles: BT, Deep Channel: Afro Celts, Listen:
Tahiti 80, Listen: Tahiti 80, Listen: Tahiti 80, Passenger:
Headmix, Pink Moon: Nick Drake, Shiva Moon: Prem Joshua,
Somersault: Zero 7]
[Deep Channel: Afro Celts, Circles: BT, Circles: BT, Passenger:
Headmix, Pink Moon: Nick Drake, Shiva Moon: Prem Joshua, Listen:
Tahiti 80, Listen: Tahiti 80, Listen: Tahiti 80, Somersault:
Zero 7]
B---- :--l-
SongListMore,tt
Pink Moon/Nick Drake/5/80
Somersault/Zero 7/4/84
Shiva Moon/Prem Joshua/6/120
Circles/BT/5/110
Deep Channel/Afro Celts/4/120
Passenger/Headmix/4/100
Listen/Tahiti 80/5/90
Listen/Tahiti 80/5/90
Listen/Tahiti 80/5/90
Circles/BT/5/110
1- --|:lM--- l-l |- --- .: -|:.l-: -
l, -:.-:- l- --- -.:-- : --l- ---] :--
|.]-, - ---- ----] -:- l- |.] |:l--'
l--- l--: - . ---, -||--- ] c-:|-:', . :--
l.l . --- |.]- -.-|--
w- :.-'l :.-- l- -.] l- l-l |- : --ll--
-:.-:- :---l--: --'-- -- l- --- .|| l.l
----.l-- w- .- l- :.-- l- .. :--
Al-- :--l- -:-
l- --': ---
:--.--1-|` --l-
|:--l ] ll|-`
Al-- :--l- -:-
l- A-l:lc--.--
c--.-.l-- |:--l ]
.-l:l -.--`
deaIing with dupIicates
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 557
Iiom ihc Collcciion API, wc hnu ihicc main inicilaccs, List, Sct, anu
Map. AiiayIisi is a List, lui ii looIs liIc is cxacily whai wc nccu.
Wc ncc4 z 8c! |ns!cz4 ef z I|s!
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
the coIIections API
558 chapter 16
hash8et
3et
extends
implements
implementation class
interface
Collection
[interfece}
3et
[interfece}
List
[interfece}
3orted3et
[interfece}
Ye
[interfece}
3ortedYe
[interfece}
L|nkedL|st Vector
Tree8et L|nkedhash8et hash8et ArrayL|st
TreeHap hashtab|e L|nkedhashHap hashHap
Ihc 0e||cr!|en || |pzr! ef | !I
Noiicc ihai ihc Ma inicilacc uocsn`i
aciually cxicnu ihc Collcciion inicilacc,
lui Ma is siill consiucicu aii ol ihc
Collcciion IiamcwoiI" also Inown
as ihc Collcciion API"). So Mas aic
siill collcciions, cvcn ihough ihcy uon`i
incluuc |ava.uiil.Collcciion in ihcii
inhciiiancc iicc.
Noic: ihis is noi ihc comlcic
collcciion API, ihcic aic oihci
classcs anu inicilaccs, lui
ihcsc aic ihc oncs wc caic
mosi aloui.)
M.: --'l -l-- ---
..-l|c-||-:l--, -l
l-]'-- :l|| :--:---
l- - .-l - l-
:-||-:l--: -.-----'
- ).. - . M. :
:l|| ------ l- .: .
:-||-:l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 559
Wc auucu on io ihc ]uIclox io ui ihc songs in a HashSci. Noic: wc lcli oui somc
ol ihc ]uIclox couc, lui you can coy ii liom cailici vcisions. Anu io maIc ii casici
io icau ihc ouiui, wc wcni lacI io ihc cailici vcision ol ihc Song`s ioSiiing)
mcihou, so ihai ii iinis only ihc iiilc insicau ol iiilc aiiisi.)
0s|n] z Hzsh8c! |ns!cz4 ef rrzyI|s!
import java.util.*;
import java.io.*;
public class Jukebox6 {
ArrayList<Song> songList = new ArrayList<Song>();
// main method etc.
public void go() {
getSongs();
System.out.println(songList);
Collections.sort(songList);
System.out.println(songList);
HashSet<Song> songSet = new HashSet<Song>();
songSet.addAll(songList);
System.out.println(songSet);
}
// getSongs() and addSong() methods
}
File Edit Window Help GetBetterMusic
%java Jukebox6
[Pink Moon, Somersault, Shiva Moon, Circles, Deep Channel,
Passenger, Listen, Listen, Listen, Circles]
[Circles, Circles, Deep Channel, Listen, Listen, Listen,
Passenger, Pink Moon, Shiva Moon, Somersault]
[Pink Moon, Listen, Shiva Moon, Circles, Listen, Deep Channel,
Passenger, Circles, Listen, Somersault]
+--- -- :--.l- . --- +.:-l
.-.--l---- l- -| --:
w- -'l :.-- -l--:|`, :- l :l|| -l: l- :--: - .- A--.]|:l
+.:-l .: . :-|- .A|||` --l- l.l :.-
l.- .--l-- :-||-:l-- .- -:- l l- --|.l-
l- +.:-l |l': l- :.-- .: -- .- -.:
:-- --- .l . l-- |-:-l --: :-|--`
1- -l -'l -|''
w- :l|| .- .|| l- -|:.l-: '
B---- :--l-
l- A--.]|:l
Al-- :--l-
l- A--.]|:l
|] ll|-`
Al-- -ll- l
-l- . +.:-l,
.- --l- l-
+.:-l |-- -'l
:.|| :--l|` ..-`
|A- l |-:l l: :--l ----
--- -- -l l- |:l -l- .
+.:-l, -l --'|| ----] .--l
l.l --- |.l--`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
560 chapter 16
Whz! mzkcs ! we e|jcr!s cez| !
Iiisi, wc havc io asI-whai maIcs iwo Song iclcicnccs
uulicaics. Thcy musi lc consiucicu . Is ii simly iwo
iclcicnccs io ihc vciy samc ol|cci, oi is ii iwo scaiaic ol|ccis
ihai loih havc ihc samc .Ie.
This liings u a Icy issuc: .ee.ere cqualiiy vs. obe cqualiiy.
Reference equality
Two references, one object on the heap.
t|t|e: 6|rc|es
hash6ode: 254
Ob]ect equality
Two references, two objects on the heap, but
the objects are cons|dered meeningfully equivelent.
Song
hash6ode(}
7
4
2
hash6ode(}
742
t|t|e: 6|rc|es
hash6ode: 742
t|t|e: 6|rc|es
hash6ode: 742
hash8et
Your hoshcodes
ore fhe some, buf ore
you PEALLY equoI7
6-:l ]--'-- l-]-
l- . ---: l: --.|:|`
--l-, :--.-- l:-|
l- .-, .- --l---: l---
6-:l .|--.] |N
l- +.:-l
Song
Song
equa|s( bar }
tru
e
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
562 chapter 16
Ihc 8en] r|zss w| !h evcrr|44cn
hzsh0e4c|I zn4 cez|s|I
class Song implements Comparable<Song>{
String title;
String artist;
String rating;
String bpm;
public boolean equals(Object aSong) {
Song s = (Song) aSong;
return getTitle().equals(s.getTitle());
}
public int hashCode() {
return title.hashCode();
}
public int compareTo(Song s) {
return title.compareTo(s.getTitle());
}
Song(String t, String a, String r, String b) {
title = t;
artist = a;
rating = r;
bpm = b;
}
public String getTitle() {
return title;
}
public String getArtist() {
return artist;
}
public String getRating() {
return rating;
}
public String getBpm() {
return bpm;
}
public String toString() {
return title;
}
}
1- +.:-l |-- .-]--- -|:- :.||- l:
--l-` :--: l .--l-- --
1- 6!A1 ---: : l.l ll|- : . l--,
.- l--: .- .- ------ --.|:|`
--l- - .|| -- .- l- - : .: ---
ll|- l': --.| l- l- -l-- :--': ll|-
.-- -.| --- l- l-- :|.:: .: .- ------
.:c--|` --l-, :- ]-- :.- -:l --l--- l- --:-|l -
:.||- .:c--|` -- l- ll|- N-l:- -- .:c--|`
.- --.|:|` .-- -:- l- AM! -:l.-:- .-.|-
%java Jukebox6
[Pink Moon, Somersault, Shiva Moon, Circles,
Deep Channel, Passenger, Listen, Listen,
Listen, Circles]
[Circles, Circles, Deep Channel, Listen,
Listen, Listen, Passenger, Pink Moon, Shiva
Moon, Somersault]
[Pink Moon, Listen, Shiva Moon, Circles,
Deep Channel, Passenger, Somersault]
File Edit Window Help RebootWindows
N-- l ---:' N- -|:.l-: --- --
--l --l l- +.:-l B-l -- -'l
:.|| :--l|` ..-, .- --- -- -l
l- A--.]|:l -l- l- +.:-l, l-
+.:-l -'l --:--- l- :--l ----
overriding hashCode() and equaIs()
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
coIIections with generics
you are here 563
Java Ob]ect Law For HashCode{}
and equals{}
The AP docs for class Ob]ect state the
rules you MU8T follow:
The elements in
the list must be of a type that
implements Comparable
T|e 8oo| c|ass or l|e prev|ous
pae d|dr'l |rp|ererl Corparao|e, so |l
Wou|dr'l Wor| al rurl|re. T||r| aooul |l, l|e
poor Tree3el's so|e purpose |r ||le |s lo |eep
your e|ererls sorled, ard orce aa|r|l |ad
ro |dea |oW lo sorl 8oo| oojeclsl ll doesr'l la||
al corp||e-l|re, oecause l|e Tree3el add()
rel|od doesr'l la|e a Corparao|e lype,T|e
Tree3el add() rel|od la|es W|alever lype
you used W|er you crealed l|e Tree3el. lr
ol|er Words, |l you say reW Tree3el<8oo|>()
l|e add() rel|od |s esserl|a||y add(8oo|). Ard
l|ere's ro requ|rererl l|al l|e 8oo| c|ass
|rp|ererl Corparao|el 8ul |l la||s al rurl|re
W|er you add l|e secord e|ererl lo l|e sel.
T|al's l|e l|rsl l|re l|e sel lr|es lo ca|| ore ol
l|e oojecl's corpareTo() rel|ods ard... car'l.
web 8tart
FiIe Edit View
RH| app
FiIe Edit View
8f8l 88f00ll
what are the advantages and
disadvantages of delivering your
1ava program as a local, stand-
alone application running on
the end-user's computerI
what are the advantages and
disadvantages of delivering your
1ava program as web-based
system where the user interacts
with a web browser, and the
1ava code runs as servlets on the
serverI
Executab|e
Jar
FiIe Edit View
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 583
|mz]|nc !h|s srcnzr|e...
Bol`s haily ai woiI on ihc hnal icccs ol his cool ncw
]ava iogiam. Alici wccIs ol lcing in ihc I`m-|usi-
onc-comilc-away" mouc, ihis iimc hc`s ically
uonc. Thc iogiam is a laiily sohisiicaicu
GUI a, lui sincc ihc lulI ol ii is Swing
couc, hc`s mauc only ninc classcs ol his
own.
Ai lasi, ii`s iimc io uclivci ihc iogiam io ihc
clicni. Hc hguics all hc has io uo is coy ihc
ninc class hlcs, sincc ihc clicni alicauy has
ihc ]ava API insiallcu. Hc siaiis ly uoing an
on ihc uiiccioiy whcic all his hlcs aic...
Whoa! Somcihing siiangc has hacncu. Insicau ol 1S
hlcs ninc souicc couc hlcs anu ninc comilcu class
hlcs), hc sccs S1 hlcs, many ol which havc vciy siiangc
namcs liIc:
AccouniSIilcIisicnci.class
ChaiiSSavcIisicnci.class
anu on ii gocs. Hc hau comlcicly loigoiicn
ihai ihc comilci has io gcnciaic class hlcs
loi all ihosc innci class GUI cvcni lisicncis
hc mauc, anu ihai`s whai all ihc siiangcly-
namcu classcs aic.
Now hc has io caiclully cxiiaci all ihc class
hlcs hc nccus. Il hc lcavcs cvcn onc ol ihcm oui,
his iogiam won`i woiI. Bui ii`s iiicIy sincc hc
uocsn`i wani io acciucnially scnu ihc clicni
onc ol his couc hlcs, yci cvciyihing is
in ihc samc uiiccioiy in onc lig mcss.
Whof fhe... 7
If's
fnoIIy donel
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
organizing your cIasses
584 chapter 17
%cd MyProject/classes
%java Mini
%cd MyProject/source
%javac -d ../classes MyApp.java
8cpzrz!c seerrc re4c zn4 r|zss f||cs
A singlc uiiccioiy wiih a ilc ol souicc couc anu class hlcs is a
mcss. Ii iuins oui, Bol shoulu havc lccn oiganizing his hlcs
liom ihc lcginning, Iccing ihc souicc couc anu comilcu
couc scaiaic. In oihci woius, maIing suic his comilcu class
hlcs uiun`i lanu in ihc samc uiiccioiy as his souicc couc.
The hey is o combinotion o[ directory structure orgonizotion ond the
compiIer option.
8uf I fhoughf I didn'f hove
o choice obouf puffing fhe cIoss
fIes in wifh fhe source fIes.
When you compiIe, fhey jusf go
fhere, so whof do I do7
Thcic aic uozcns ol ways you can oiganizc youi hlcs, anu youi
comany mighi havc a sccihc way ihcy wani you io uo ii. Wc
iccommcnu an oiganizaiional schcmc ihai`s lccomc almosi
sianuaiu, ihough.
Wiih ihis schcmc, you cicaic a io|cci uiiccioiy, anu insiuc
ihai you cicaic a uiiccioiy callcu sourcc anu a uiiccioiy callcu
classcs. You siaii ly saving youi souicc couc .|ava hlcs) inio
ihc sourcc uiiccioiy. Thcn ihc iiicI is io comilc youi couc
in such a way ihai ihc ouiui ihc .class hlcs) cnus u in ihc
cIosses uiiccioiy.
Anu ihcic`s a nicc comilci uag, -d, ihai lcis you uo ihai.
Compiling with the -d {directory} hag
l-||: l- :--|-- l- -l l-
:--|- :-- |:|.:: |-:`
-l- l- :|.::-: --:l--]
l.l': --- --:l--] - .-
.: --- ..- --- l-
:-----l ---- --:l--]
l- |.:l l- : :l||
l- -.-- - l- ..
|- l- :--|-
By using ihc -d uag, gci io ucciuc which directory ihc
comilcu couc lanus in, iaihci ihan accciing ihc uclauli ol
class hlcs lanuing in ihc samc uiiccioiy as ihc souicc couc.
To comilc all ihc .|ava hlcs in ihc souicc uiiccioiy, usc:
Running your code
--- ]--- ---.- ---
l- ':|.::-:' --:l--]
%javac -d ../classes *.java
.. :--|-: A||
:---:- |-: - l-
:-----l --:l--]
HyProject
source c|asses
Lorper
iure eugue
tat vero
conse
eugueroLore
do eliquis
do del dip
101101
101101
10101000010
1010 10 0
01010 1
1010101
10101010
1001010101
HyApp.java
HyApp.c|ass
:--|- ---
1+| --:l--]
:--|- :--
|.-: ---
--- ]--- -.-|`
--- ---
|l---|-:--l- --l- ---]l- - l: :.l-- .::---: l.l l-
:-----l ---- --:l--] |- l- '` : - ]--- :|.::.l | ]--
.- -|:l|] :-l . :|.::.l --------l .-.|-, - :--l.-
l.l l :--l.-: l- ' `
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 585
|e! yeer 1zvz |n z 1K
A hlc is a ava chivc. Ii`s lascu on ihc Izi hlc loimai, anu ii lcis you lunulc
all youi classcs so ihai insicau ol icscniing youi clicni wiih 2S class hlcs, you hanu
ovci |usi a singlc ]AR hlc. Il you`ic lamiliai wiih ihc iai commanu on UNIX, you`ll
iccognizc ihc |ai iool commanus. Noic: whcn wc say ]AR in all cas, wc`ic iclciiing
io ihc aichivc Ie. Whcn wc usc lowcicasc, wc`ic iclciiing io ihc n. ooI you usc io
cicaic ]AR hlcs.)
Thc qucsiion is, whai uocs ihc clicni Jo wiih ihc ]AR. How uo you gci ii io .ur.
You maIc ihc ]AR executobIe.
An cxccuiallc ]AR mcans ihc cnu-usci uocsn`i havc io ull ihc class hlcs oui lcloic
iunning ihc iogiam. Thc usci can iun ihc a whilc ihc class hlcs aic siill in ihc
]AR. Thc iiicI is io cicaic a moni[est hlc, ihai gocs in ihc ]AR anu holus inloimaiion
aloui ihc hlcs in ihc ]AR. To maIc a ]AR cxccuiallc, ihc manilcsi musi icll ihc ]VM
wL.L In Ln Le n.r() eLoJ
JAP
101101
101101
10101000010
1010 10 0
01010 1
1010101
10101010
1001010101
Making an executable JAR
1
Muke sure uII of your cIuss h Ies ure in
the cIusses directory
We're going fo refne fhis in o few poges, buf
for now, keep oII your cIoss fIes siffing in fhe
direcfory nomed 'cIosses'.
2
Creute u munifest,tt h Ie thut stutes
which cIuss hus the muin{} method
Moke o fexf fIe nomed monifesf.fxf fhof hos o
one Iine:
Main-Class: MyApp
Press fhe refurn key offer fyping fhe Moin-
CIoss Iine, or your monifesf moy nof work
correcfIy. Puf fhe monifesf fIe info fhe "cIosses"
direcfory.
101101
101101
10101000010
1010 10 0
01010 1
1010101
10101010
1001010101
101101
101101
10101000010
1010 10 0
01010 1
1010101
10101010
1001010101
Va|r-C|ass: Vy|App
3
Pun the jur tooI to creute u JAP h Ie
thut contuins everything in the cIusses
directory pIus the munifest,
%cd MiniProject/classes
%jar -cvmf manifest.txt app1.jar *.class
OR
%jar -cvmf manifest.txt app1.jar MyApp.class
c|asses
HyProject
101101
101101
c|asses
101101
101101
101101
101101
HyProject
Va|r-C|ass: V|r|App
rar|lesl.lxl
upp1,jur
101101
101101
101101
101101
101101
101101
Va|r-C|ass: V|r|App
--'l -l l- :|.::
-- l- --
-- :---:-
:-- |..`
- l- )A
VyApp.c|ass
c|asses
rar|lesl.lxl
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
586 chapter 17
Kenn|n] |crcre!|n]I !hc 1K
]ava ihc ]VM) is caallc ol loauing a class liom a ]AR, anu calling
ihc main) mcihou ol ihai class. In laci, ihc cniiic alicaiion can
n, in ihc ]AR. Oncc ihc lall is iolling i.c., ihc main) mcihou
siaiis iunning), ihc ]VM uocsn`i caic wLe.e youi classcs comc
liom, as long as ii can hnu ihcm. Anu onc ol ihc laccs ihc ]VM
looIs is wiihin any ]AR hlcs in ihc classaih. Il ii can ee a ]AR, ihc
]VM will IooI in ihai ]AR whcn ii nccus io hnu anu loau a class.
%cd MyProject/classes
%java -jar app1.jar
upp1,jur
101101
101101
101101
101101
101101
101101
Va|r-C|ass: V|r|App
c|asses
1- )/M .: l- ':--' l- )A, :-
l --:l - - ]--- :|.::.l 1-
-.:-:l -.] l- -.- l- )A :|-
: l- -.- ]--- ---- --:l--]
l- |.:- ---- l- )A :
1- ~.- |. l-||: l- )/M ]--'-- - l . )A -:l-. - . :|.::
1
- )/M
|--: -:- l: )A
--
. -.--:l -l .- --l-] -- M
.-~
c|.:: | l --:-'l - ---, ]-- -l
. ---l-- -:-l--
Dccnuing on how youi ociaiing sysicm is conhguicu, you
mighi cvcn lc allc io simly uoullc-clicI ihc ]AR hlc io launch
ii. This woiIs on mosi uavois ol Winuows, anu Mac OS X. You
can usually maIc ihis hacn ly sclcciing ihc ]AR anu iclling
ihc OS io Ocn wiih..." oi whaicvci ihc cquivalcni is on youi
ociaiing sysicm).
- :
|.
:: -
.
-
- :
.
|-
.
]
: :
.
l
.
|-
-
---:l:c.-l -l - . :-----
-.--, -l .- :---.-:l..
--.-: -- .- l- ----] .--l --|]
--- --- -~--:- --|---:
]ze[zg, ezn vn( nz
en|]je(,, a( n]y j| ya
e[, z ze[zg nz
([z(', gazzn(] (
anjga. [[ ,( wzy (
] ([z( j, ( |ze ya
ze[zg, wj([ ya v,
]zjn nz.
com.heodfrsfbooks.8ook
.:.- -.--
:
|.
:: -
.
-
-
package naming
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 589
p
o
c
k
o
g
e
s
f
r
u
c
f
u
r
e
HyProject
source c|asses
101101
101101
10101000010
1010 10 0
01010 1
1010101
10101010
1001010101
PackageExerc|se.c|ass
com
heedfirstjeve
com
heedfirstjeve
Lorper
iure eugue
tat vero
conse
eugueroLore
do eliquis
do del dip
PackageExerc|se.java
1
Choose u puckuge nume
We're using com,heudhrstjuvu os our
exompIe. The cIoss nome is PockogeExercise,
so fhe fuIIy-quoIifed nome of fhe cIoss is now:
com,heudhrstjuvu,PuckugeEercise.
To put your class in a package:
2
Put u puckuge stutement in your cIuss
package com.head rstjava;
import javax.swing.*;
public class PackageExercise {
// life-altering code here
}
3
Set up u mutching directory structure
If musf be fhe frsf sfofemenf in fhe source
code fIe, obove ony imporf sfofemenfs. There
con be onIy one pockoge sfofemenf per source
code fIe, so uII cIusses in u source hIe must
be in the sume puckuge. Thof incIudes inner
cIosses, of course.
If's nof enough fo suy your cIoss is in o pockoge,
by mereIy puffing o pockoge sfofemenf in
fhe code. Your cIoss isn'f fruIy in o pockoge
unfiI you puf fhe cIoss in o mofching direcfory
sfrucfure. So, if fhe fuIIy-quoIifed cIoss nome
is com.heodfrsfjovo.PockogeExercise, you
must puf fhe PockogeExercise source code in o
direcfory nomed heudhrstjuvu, which must be in
o direcfory nomed com.
If is possibIe fo compiIe wifhouf doing fhof, buf
frusf us-if's nof worfh fhe ofher probIems
you'II hove. Ieep your source code in o direcfory
sfrucfure fhof mofches fhe pockoge sfrucfure,
ond you'II ovoid o fon of poinfuI heodoches down
fhe rood.
You must put a class
into a directory
structure that matches
the package hierarchy.
Sef up o mofching direcfory sfrucfure for
bofh fhe source ond cIosses frees.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
590 chapter 17
%cd MyProject/classes
%java com.head rstjava.PackageExercise
%cd MyProject/source
%javac -d ../classes com/head rstjava/PackageExercise.java
Compiling with the -d {directory} hag
l-||: l- :--|-- l- -l l-
:--|- :-- |:|.:: |-:`
-l- l- :|.::-: --:l--],
-l- l- -l .:.-
:l--:l---'' /-:, l ---:
N-- ]-- .- l- :-:]
l- |A1+ l- -l l- l-
.:l-.| :---:- |-
To comilc all ihc .|ava hlcs in ihc com.hcauhisi|ava
acIagc, usc:
Running your code
--- ]--- ---.- ---
l- ':|.::-:' --:l--]
%javac -d ../classes com/head rstjava/*.java
0emp|||n] zn4 renn|n] w| !h pzrkz]cs
Whcn youi class is in a acIagc, ii`s a liiilc iiicIici io comilc anu
iun. Thc main issuc is ihai loih ihc comilci anu ]VM havc io lc
caallc ol hnuing youi class anu all ol ihc oihci classcs ii uscs.
Ioi ihc classcs in ihc coic API, ihai`s ncvci a iollcm. ]ava always
Inows whcic iis own siull is. Bui loi youi classcs, ihc soluiion
ol comiling liom ihc samc uiiccioiy whcic ihc souicc hlcs aic
simly won`i woiI oi ai lcasi noi ). Wc guaianicc, ihough,
ihai il you lollow ihc siiuciuic wc ucsciilc on ihis agc, you`ll lc
succcsslul. Thcic aic oihci ways io uo ii, lui ihis is ihc onc wc`vc
lounu ihc mosi icliallc anu ihc casicsi io siicI io.
HyProject
source c|asses
101101
10 110 1
0 11 0
001 10
001 01
PackageExerc|se.c|ass
com
heedfirstjeve
com
heedfirstjeve
Lorper
iure
eugue
tat vero
conse
euguero-
PackageExerc|se.java
]--'|| :l|| :--|-
--- ---
:l.] - l- :---:- --:l--]' l- N61 : ---
-l- l- --:l--] ---- l- .. |- :'
:--|-: ---] :---:- |..` |- - l: --:l--]
/-- Mc1 - l- -||]~-.|- :|.:: -.--' 1- )/M -||
:-- l.l, .- ---.l-|] |-- -:- l: :-----l --:l--]
|:|.::-:` .- --:l l- - . --:l--] -.-- :--, ----
l --:l: l- - . --:l--] -.-- -.-:l.., .- -
l--- l --:l: l- - l- :|.:: | l- :|.:: : - l- :--'
--:l--], -- --- - :|.::-:', l ---'l ---'
]
-
-'|| :l
|| -
--
-
-
-
--
-
compiIe and run with packages
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 591
(-,- a,- |
oa|| qa--(:|-
I tried to cd into the
directory where my main cIass
was, but now the 1VM says it can't
nd my cIassl ut it's right 7HR
in the current directoryl
Once your class is in a
package, you can't call it by its
'short' name. ou MUST specify,
at the command-line, the fully-
qualified name of the class whose
main() method you want to run.
8ut since the fully-qualified name
includes the ocloe structure,
1ava insists that the class be in a
matching J|tectoty structure. So if
at the command-line you say:
%ava com.foo.Book
the 1vM will look in its current
directory (and the rest of its
classpath), for a directory named
"com. lr will ner leek Ier n clnss
nnmeJ 8eek, unril ir hns IeunJ
n Jirecrery nnmeJ "cem" wirh n
Jirecrery insiJe nnmeJ "Iee". Only
then will the 1vM accept that its
found the correct 8ook class. |f it
finds a 8ook class anywhere else,
it assumes the class isn't in the
right structure, even if it is! The
1vM won't for example, look back
up the directory tree to say, "Oh, |
can see that above us is a directory
named com, so this must be the
right package...
Ihc -4 f|z] |s cvcn ree|cr !hzn wc sz|4
Comiling wiih ihc -d uag is wonucilul lccausc noi only uocs ii
lci you scnu youi comilcu class hlcs inio a uiiccioiy oihci ihan
ihc onc whcic ihc souicc hlc is, lui ii also Inows io ui ihc class
inio ihc coiicci uiiccioiy siiuciuic loi ihc acIagc ihc class is in.
Bui ii gcis cvcn lciici!
Ici`s say ihai you havc a nicc
uiiccioiy siiuciuic all sci u loi youi
souicc couc. Bui you havcn`i sci
u a maiching uiiccioiy siiuciuic
loi youi classcs uiiccioiy. Noi a
iollcm! Comiling wiih
-u iclls ihc comilci io noi
|usi youi classcs inio ihc
coiicci uiiccioiy iicc, lui io
ihc uiiccioiics il ihcy uon`i cxisi.
HyProject
source c|asses
com
heedfirstjeve
Lorper
iure
eugue
tat vero
conse
euguero-
PackageExerc|se.java
| l- .:.- --:l--] :l--:l---
--:-'l -:l ---- l- ':|.::-:'
--:l--], l- :--|-- -|| -| l-
--:l---: ]-- -:- l- ~ |.
- ]-- --'l .:l-.||] .- l-
]::.||] :--.l- l- --:l---: ----
l- ':|.::-:' ---l --:l--] A- -
.:l, ]-- |-l l- :--|-- - l
l---': -- :.-:- - . l]-
The -d hag tells the compiler,
Put the class into its package
directory structure, using the
class specihed after the -d as
the root directory. But... if the
directories aren't there, create
them hrst and then put the class
in the right placel
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
592 chapter 17
Whcn youi class is in a acIagc, ihc acIagc uiiccioiy siiuciuic
musi lc insiuc ihc ]AR! You can`i |usi o youi classcs in ihc
]AR ihc way wc uiu ic-acIagcs. Anu you musi lc suic ihai you
uon`i incluuc any oihci uiiccioiics alovc youi acIagc. Thc
hisi uiiccioiy ol youi acIagc usually com) musi lc ihc hisi
uiiccioiy wiihin ihc ]AR! Il you wcic io acciucnially incluuc ihc
uiiccioiy ihc acIagc c.g. ihc classcs" uiiccioiy), ihc ]AR
woulun`i woiI coiiccily.
PackageExerc|se.c|ass
c|asses
com
heedfirstjeve
101101
10 110 1
0 11 0
001 10
001 01
Mzk|n] zn crcre!z||c 1K w| !h pzrkz]cs
JAP
Making an executable JAR
1
Muke sure uII of your cIuss h Ies ure
within the correct puckuge structure
under the cIusses directory,
2
Creute u munifest,tt h Ie thut stutes
which cIuss hus the muin{} method
und be sure to use the fuIIy-quuIih ed
cIuss nume|
Moke o fexf fIe nomed monifesf.fxf fhof hos o
singIe Iine:
Main-Class: com.head rstjava.PackageExercise
Puf fhe monifesf fIe info fhe cIosses direcfory
3
Pun the jur tooI to creute u JAP h Ie
thut contuins the puckuge directories
pIus the munifest
%cd MyProject/classes
%jar -cvmf manifest.txt packEx.jar com
puckE,jur
c|asses
man|fest.txt
c|asses
com
heedfirstjeve
101101
10 110 1
0 11 0
001 10
001 01
Va|r-C|ass: V|r|App
PackageExerc|se.c|ass
com
heedfirstjeve
101101
10 110 1
0 11 0
001 10
001 01
PackageExerc|se.c|ass
A|| ]-- :-:] : l-
:-- --:l--]' A- ]--'||
-l ---]l- - l'
The onIy fhing you need fo incIude is fhe 'com'
direcfory, ond fhe enfire pockoge (ond oII cIosses)
wiII go info fhe JAP.
JARs and packages
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 593
8e whcrc 4|4 !hc mzn|fcs! f||c ]e!
~l :l.-: -- '1.|- ||-' .: -
:-- -- . l.|- - l- )A |-'
-- -l l- )A
|- -l- .
--:l--] -.-- ]|--
Why uon`i wc looI insiuc ihc ]AR anu hnu oui. Iiom ihc
commanu-linc, ihc |ai iool can uo moic ihan |usi cicaic anu iun a
]AR. You can cxiiaci ihc conicnis ol a ]AR |usi liIc unziing` oi
uniaiiing`).
Imaginc you`vc ui ihc acIEx.|ai inio a uiiccioiy namcu SIylci.
eckEx.jer
]ar commands for listing and extracting
1
List the contents of u JAP
% jar -tf packEx.jar
File Edit Window Help Pickle
% cd Skyler
% jar -tf packEx.jar
META-INF/
META-INF/MANIFEST.MF
com/
com/headfirstjava/
com/headfirstjava/
PackageExercise.class
~ :l.-: -- '!l-.:l ||-' .- l
---: -:l |- ---- -- --l.---
| ]-- -l-.:l l- .:!.-, ]--'||
:-- l- M!1A~|N| --:l--] .- l-
:-- --:l--] --:l--] - ]--- :-----l
--:l--]
2
Etruct the contents of u JAP {i,e, unjur}
% cd Skyler
% jar -xf packEx.jar
HAN|FE8T.HF
Va|r-C|ass: V|r|App
com
heedfirstjeve
PackageExerc|se.c|ass
YE7A-/hF
8ky|er
l- .- l--| .-l--.l:.||]
-|: . M
!1
A
~|N|
--:l--], .- -l: l-
-.--:l -:-
101101
10 110 1
0 11 0
001 10
001 01
8ky|er
HAN|FE8T.HF
Va|r-C|ass: V|r|App
com
heedfirstjeve
YE7A-/hF
PackageExerc|se.c|ass
101101
10 110 1
0 11 0
001 10
001 01
META-IMF sfonds for 'mefo
informofion'. The jor fooI creofes
fhe META-IMF direcfory os
weII os fhe MAMIFEST.MF fIe.
If oIso fokes fhe confenfs of
your monifesf fIe, ond pufs if
info fhe MAMIFEST.MF fIe. So,
your monifesf fIe doesn'f go info
fhe JAP, buf fhe confenfs of if
ore puf info fhe 'reoI' monifesf
(MAMIFEST.MF).
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
organizing your cIasses
594 chapter 17
+,-+ :+ ,-+:.|
Foof.c|ass
c|asses
101101
10 110 1
0 11 0
001 10
001 01
Given the package/directory structure in this
picture, gure out what you should type at the
command-line to compile, run, create a 1AP, and
execute a 1AP. Assume we're using the standard
where the package directory structure starts |ust
below soutce and closses. |n other words, the soutce
and closses directories are not part of the package.
%cd source
%javac ________________________________
javaranch
cows
CompiIe:
%cd ___________
%java _________________________________
Pun:
%cd ___________
%______________________________________
Creute u JAP
man|fest.txt
Va|r-C|ass: V|r|App
source
javaranch
cows
Lorper
iure
eugue
tat vero
conse
euguero-
Foof.java
HyProject
%cd ___________
% _____________________________________
Eecute u JAP
8onus question: what's wrong with the package nameI
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 595
8ll P0lk5
0rar|ze your projecl so l|al your source code ard c|ass l||es are rol |r
l|e sare d|reclory.
A slardard orar|zal|or slruclure |s lo creale a rojeor d|reclory, ard l|er
pul a souroe d|reclory ard a o|asses d|reclory |rs|de l|e projecl d|reclory.
0rar|z|r your c|asses |rlo pac|aes preverls rar|r co|||s|ors W|l|
ol|er c|asses, |l you preperd your reverse dora|r rare or lo l|e lrorl ol
a c|ass rare.
To pul a c|ass |r a pac|ae, pul a pac|ae slalererl al l|e lop ol l|e
source code l||e, oelore ary |rporl slalererls:
package com.wickedlysmart;
To oe |r a pac|ae, a c|ass rusl oe |r a o|reorory srruorure rnar exaor|y
marones rne aokage srruorure. For a c|ass, cor.W|c|ed|ysrarl.Foo,
l|e Foo c|ass rusl oe |r a d|reclory rared u|okeo|ysmarr, W||c| |s |r a
d|reclory rared oom.
To ra|e your corp||ed c|ass |ard |r l|e correcl pac|ae d|reclory
slruclure urder l|e o|asses d|reclory, use l|e -d corp||er l|a:
% cd source
javac -d ../classes com/wickedlysmart/Foo.java
To rur your code, cd lo l|e c|asses d|reclory, ard |ve l|e lu||y-qua||l|ed
rare ol your c|ass:
% cd classes
java com.wickedlysmart.Foo
You car ourd|e your c|asses |rlo JAR (Java ARc||ve) l||es. JAR |s oased
or l|e p|z|p lorral.
You car ra|e ar execulao|e JAR l||e oy pull|r a rar|lesl |rlo l|e JAR
l|al slales W||c| c|ass |as l|e ra|r() rel|od. To creale a rar|lesl l||e,
ra|e a lexl l||e W|l| ar erlry |||e l|e lo||oW|r (lor exarp|e):
Main-Class: com.wickedlysmart.Foo
8e sure you ||l l|e relurr |ey aller lyp|r l|e Va|r-C|ass ||re, or your
rar|lesl l||e ray rol Wor|.
To creale a JAR l||e, lype:
jar -cvfm manifest.txt MyJar.jar com
T|e erl|re pac|ae d|reclory slruclure (ard on|y l|e d|reclor|es ralc||r
l|e pac|ae) rusl oe |rred|ale|y |rs|de l|e JAR l||e.
To rur ar execulao|e JAR l||e, lype:
java -jar MyJar.jar
(-,- a,- |
oa|| qa--(:|-
web 8tart
FiIe Edit View
RH| app
FiIe Edit View
Executab|e
Jar
FiIe Edit View
web 8tart
FiIe Edit View
: -- l- :----
w
-'-- l-:l- l: -- --- |-:.|-:l, :- -
-'-- -:-
l- |-:.| |--.: .
--:: |i
7
o
o
|' |
-- -
-
:l.-l .: -- --- -l----l -
- :----, l: -
--|
:.], ll//-
-
-
-
:-
|]:-
.-l:--
'
1: : l- |-:.l-- - l- -| |- --|.l- l- l-
:--.:- 1: -.-|- :--: l.l M]A-| :
..|.|- - l- ---l --:l--] - l- -- :----, --l
--:l- - :--- -l-- --:l--]
B- :--- l- -:|-- .|| - l-:- l.:, -- ]--- . -l
--l --- :----:l|]' 1- '----.l--' l.: .-- -:- ]
l- )w -|-- ., --:l|] -- :|.]- --- l- -:--
-.-l: l- --|.--: . ----:|]~---|-.- .|:.l--
1: --.-: l- -:-- :.- --- ]--- ---.- -l--l
-- :----:l- l- l- -l----l | l- -:-- : -|--,
l --.-: l- .-l--.l:~-.l- -.l--- ---'l ---
1: :.]: l.l ]--- . ---: --:-- |?
- ).., -- --.l--
1- -.-- - ]--- --:-l.|- )A' /-- -l .-
-l-- )A |-: .: --||, l.l -| -l-- :|.::-: --
--- :---: .- -.-: -:- ] ]--- .
1: : |- l- -.--:l M.-~c|.:: --l-] l :.]:
-: :|.:: - l- )A .: l- -.-|` --l-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
600 chapter 17
8teps for making and deploying
a Java Web 8tart app
1 Muke un eecutubIe JAP
for your uppIicution,
HyApp.jar
2 Write u ,jnIp hIe,
Lorper
iure
eugue
tat vero
conse
euguero-
HyApp.jn|p
3
Web 8erver
HyApp.jar
Lorper
iure
eugue
tat vero
conse
euguero-
roo.htm|
Lorper
<iure
eugue
tat vero
conse
HyApp.jn|p
PIuce your JAP und ,jnIp
hIes on your Web server,
4 Add u new mime type to your Web server,
This couses fhe server fo send fhe .jnIp fIe wifh fhe
correcf heoder, so fhof when fhe browser receives
fhe .jnIp fIe if knows whof if is ond knows fo sforf
fhe JWS heIper opp.
application/x-java-jnlp-le
Web 8erver
conhgure
mime type
5 Creute u Web puge with u Iink
to your ,jnIp hIe
<HTML>
<BODY>
<a href=MyApp2.jnlp>Launch My Application</a>
</BODY>
</HTML>
Lorper
iure
eugue
tat vero
conse
euguero-
HyJw8App.htm|
depIoying with JWS
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 601
yg'z
]j;z/
8ll P0lk5
Java weo 3larl lec|ro|oy |els you dep|oy a
slard-a|ore c||erl app||cal|or lror l|e weo.
Java weo 3larl |rc|udes a '|e|per app' l|al rusl
oe |rsla||ed or l|e c||erl (a|or W|l| Java).
A Java weo 3larl (Jw3) app |as lWo p|eces:
ar execulao|e JAR ard a .jr|p l||e.
A .jr|p l||e |s a s|rp|e XVL docurerl l|al
descr|oes your Jw3 app||cal|or. ll |rc|udes
las lor spec|ly|r l|e rare ard |ocal|or ol l|e
JAR, ard l|e rare ol l|e c|ass W|l| l|e ra|r()
rel|od.
w|er a oroWser els a .jr|p l||e lror l|e server
(oecause l|e user c||c|ed or a ||r| lo l|e .jr|p
l||e), l|e oroWser slarls up l|e Jw3 |e|per app.
T|e Jw3 |e|per app reads l|e .jr|p l||e ard
requesls l|e execulao|e JAR lror l|e weo
server.
w|er l|e Jw3 els l|e JAR, |l |rvo|es l|e
ra|r() rel|od (spec|l|ed |r l|e .jr|p l||e).
l.
2.
3.
4.
5.
6.
7.
Look at the sequence of events below, and
place them in the order in which they
occur in a 1wS application.
user c||c|s a weo pae ||r|
oroWser requesls a .jr|p l||e
lror l|e weo server
l|e weo server serds a .jr|p
l||e lo l|e oroWser
l|e weo oroWser slarls up
l|e Jw3 |e|per app
l|e Jw3 |e|per app requesls
l|e JAR l||e
l|e weo server serds a JAR
l||e lo l|e Jw3 |e|per app
l|e Jw3 |e|per app |rvo|es
l|e JAR's ra|r() rel|od
(-,- a,- |
oa|| qa--(:|-
How is 1ava Web Start different from an appIet!
Applets can't live outside of a web browser. An applet is
downloaded from the web as part of a web page rather than
simply from a web page. |n other words, to the browser, the applet
is |ust like a 1PLG or any other resource. The browser uses either a
1ava plug-in or the browser's own built-in 1ava (far less common
today) to run the applet. Applets don't have the same level of
functionality for things such as automatic updating, and they must
always be launched from the browser. with 1wS applications, once
they're downloaded from the web, the user doesn't even have to
be using a browser to relaunch the application locally. |nstead,
the user can start up the 1wS helper app, and use it to launch the
already-downloaded application again.
What are the security restrictions of 1WS!
1wS apps have several limitations including being
restricted from reading and writing to the user's hard drive. 8ut...
1wS has its own AP| with a special open and save dialog box so
that, with the user's permission, your app can save and read its
own files in a special, restricted area of the user's drive.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
602 chapter 17
l. Pushy widgets
2. ____ of my desire
3. 'Abandoned' moniker
4. A chunk
5. Math not trig
6. 8e brave
7. Arrange well
8. Swing slang
ll. |/O canals
l3. Organized release
l4. Not for an instance
6. won't travel
9. Don't split me
l0. Pelease-able
ll. Got the key
l2. |/O gang
l5. Platten
l7. Lncapsulated returner
l8. Ship this one
2l. Make it so
22. |/O sieve
25. Disk leaf
26. Mine is unique
27. GU|'s target
29. 1ava team
30. Pactory
32. Por a while
33. Atomic ` 8
35. Good as new
37. Pairs event
4l. where do | start
42. A little rewall
l6. who's allowed
l9. Lfciency expert
20. Larly exit
2l. Common wrapper
23. es or no
24. 1ava |ackets
26. Not behavior
28. Socket's suite
l
l7
25
29
33
4l 42
2 3 4 5 6 7 8
ll
l2 l4 l5 l6
20 2l 22
26 27
30 32
34 35 36 37 38 39
24
3l
l8
l0
9
l9
l3
23
28
40
30. |/O cleanup
3l. Milli-nap
34. Trig method
36. Lncaps method
38. 1NLP format
39. v8's nal
40. 1ava branch
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
604 chapter 17
]e;ejze
o|ajoz
exercise soIutions
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
package, jars and depIoyment
you are here 605
l
l7
25
29
33
4l 42
2 3 4 5 6 7 8
ll
l2 l4 l5 l6
20 2l 22
26 27
30 32
34 35 36 37 38 39
24
3l
l8
l0
9
l9
l3
23
28
40
ajj|i(iss ).c
D O 0 T M T P A M S I E M T W
I 8 A T O M I C P O I
A J A P I M S Y M C H P O M I Z E D
L E 8 E T T 0
O C H A I M E D P S S A V E
0 E T 0 E X E C U T A 8 L E C T
S E P A A U C S
8 I M P L E M E M T F I L T E P
8 P M O I F S W
D I P E C T O P Y S O C I E T U S E P
M A E T P P A
P A C I A 0 E C L A S S L O O P P
P E L T L P P
8 Y T E P E S T O P E E E X T P E M E
A I E S E M X P
M A M I F E S T E M C A P S U L A T E S
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
this is a new chapter 607
Being remote doesn't have to be a bad thing. Sure, things ote easier when
all the parts of your application are in one place, in one heap, with one 1vM to rule them all. 8ut
that's not always possible. Or desirable. what if your application handles powerful computations,
but the end-users are on a wimpy little 1ava-enabled deviceI what if your app needs data
from a database, but for security reasons, only code on your server can access the databaseI
|magine a big e-commerce back-end, that has to run within a transaction-management systemI
Sometimes, part of your app must run on a server, while another part (usually a client) must
run on a J|lletent machine. |n this chapter, we'll learn to use 1ava's amazingly simple Pemote
Method |nvocation (PM|) technology. we'll also take a quick peek at Servlets, Lnterprise 1ava
8eans (L18) , and 1ini, and look at the ways in which L18 and 1ini JeenJ on PM|. we'll end the
book by writing one of the coolest things you can make in 1ava, a un|vetsol setv|ce otowset.
Distributed
Computing
18 remote depIoyment with RMI
Everyone soys Iong-
disfonce reIofionships ore hord,
buf wifh PMI, if's eosy. Mo
moffer how for oporf we reoIIy
ore, PMI mokes if seem Iike
we're fogefher.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
608 chapter 18
100% LocuI Combinution 100% Pemote
8erv|ets
HTTP
web 8tart
FiIe Edit View
HTTP
RH| app
FiIe Edit View
RMI
Executab|e
Jar
FiIe Edit View
RH| app
FiIe Edit View
RMI
So lai in ihis looI, cvciy mcihou wc`vc invoIcu has lccn on
an ol|cci iunning in ihc samc viiiual machinc as ihc callci.
In oihci woius, ihc calling ol|cci anu ihc callcc ihc ol|cci
wc`ic invoIing ihc mcihou on) livc on ihc samc hca.
Mc!he4 rz||s zrc z| wzys |c! wccn
! we e|jcr!s en !hc szmc hczp.
class Foo {
void go() {
Bar b = new Bar();
b.doStuff();
}
public static void main (String[] args) {
Foo f = new Foo();
f.go();
}
}
F
o
o obj
e
c
f
8
o
r obj
e
c
f
d
o
S
f
u
f
f
(
)
In mosf oppIicofions, when one objecf
coIIs o mefhod on onofher, bofh objecfs
ore on fhe some heop. In ofher words,
bofh ore running wifhin fhe some JVM.
--- -., l
-
- --:l
:
In ihc couc alovc, wc Inow ihai ihc Ioo insiancc
iclcicnccu ly anu ihc Bai ol|cci iclcicnccu ly b aic
loih on ihc samc hca, iun ly ihc samc ]VM. Rcmcmlci,
ihc ]VM is icsonsillc loi siulhng liis inio ihc iclcicncc
vaiiallc ihai icicscni Low o e o nr obe or Le Len.
Thc ]VM always Inows whcic cach ol|cci is, anu how io
gci io ii. Bui ihc ]VM can Inow aloui iclcicnccs on only
iis owr hca! You can`i, loi cxamlc, havc a ]VM iunning
on onc machinc Inowing aloui ihc hca sacc ol a ]VM
iunning on a J.e.er machinc. In laci, a ]VM iunning on
onc machinc can`i Inow anyihing aloui a uillcicni ]VM
iunning on ihc ne machinc. Ii maIcs no uillcicncc il
ihc ]VMs aic on ihc samc oi uillcicni hysical machincs,
ii maiicis only ihai ihc iwo ]VMs aic, wcll, iwo uillcicni
invocaiions ol ihc ]VM.
how many heaps?
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 609
Wc Inow how io gci inloimaiion liom onc machinc io anoihci-
wiih SocIcis anu I/O. Wc ocn a SocIci conncciion io anoihci
machinc, anu gci an OuiuiSiicam anu wiiic somc uaia io ii.
Bui whai il wc aciually wani io nII n eLoJ on somcihing iunning
in anoihci machinc... anoihci ]VM. Ol couisc wc coulu always luilu
oui own ioiocol, anu whcn you scnu uaia io a ScivciSocIci ihc
scivci coulu aisc ii, hguic oui whai you mcani, uo ihc woiI, anu
scnu lacI ihc icsuli on anoihci siicam. Whai a ain, ihough. ThinI
how much nicci ii woulu lc io |usi gci a iclcicncc io ihc ol|cci on
ihc oihci machinc, anu call a mcihou.
Whz! |f yee wzn! !e |nvekc z mc!he4 en
zn e|jcr! renn|n] en zne!hcr mzrh|nc!
!ag:ae tva :aate:s...
5:g has saeth:ag I:tt|e vaats.
Caate ave:.
I:tt|e vaats ta seaJ sae Jata ta 5:g, sa that 5:g :aa Ja the
heavy :aat:ag.
I:tt|e vaats s:|y ta :a|| a ethaJ...
double doCalcUsingDatabase(CalcNumbers numbers)
aaJ get la:| the :esa|t.
5at hav :aa I:tt|e get a :eIe:ea:e ta aa ale:t aa 5:g!
LiffIe 8ig
-----|, .:l, |--:
l- :---: l---
:.|:-|.l--:
l-], --], .--||]
:|-- .l :.|:-|.l--:
JVM
JVM
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
two objects, two heaps
610 chapter 18
Thc qucsiion is, how uo wc gci an ol|cci on onc machinc
which mcans a uillcicni hca/]VM) io call a mcihou on
anoihci machinc.
0|jcr! , renn|n] en I| !!|c, wzn!s !e rz||
z mc!he4 en 0|jcr! B, renn|n] en B|].
A
8
doCoIcUsingDofobose()
refurn voIue
Wcll, noi uiiccily anyway. You can`i gci a iclcicncc io
somcihing on anoihci hca. Il you say:
Dog u ...
Whaicvci J is iclcicncing musi lc in ihc samc hca sacc as
ihc couc iunning ihc siaicmcni.
Bui imaginc you wani io ucsign somcihing ihai will usc
SocIcis anu I/O io communicaic youi inicniion a mcihou
invocaiion on an ol|cci iunning on anoihci machinc), yci
siill eeI as ihough you wcic maIing a local mcihou call.
In oihci woius, you wani io causc a mcihou invocaiion on a
.eoe ol|cci i.c., an ol|cci in a hca somcwhcic clsc), lui
wiih couc ihai lcis you .eerJ ihai you`ic invoIing a mcihou
on a local ol|cci. Thc casc ol a lain olu cvciyuay mcihou
call, lui ihc owci ol icmoic mcihou invocaiion. Thai`s oui
goal.
Thai`s whai RMI Rcmoic Mcihou Invocaiion) givcs you!
Bui lci`s sic lacI anu imaginc how you woulu ucsign RMI il
you wcic uoing ii youiscll. Unucisianuing whai you`u havc io
luilu youiscll will hcl you lcain how RMI woiIs.
Be! yee rzn! 4e !hz!.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 611
A design for remote method calls
Create four things: server, client,
server helper, client helper
1
Creofe cIienf ond server opps. The server opp is fhe
remote service fhof hos on objecf wifh fhe mefhod
fhof fhe cIienf wonfs fo invoke.
S
e
r
v
ice o
b
j
e
c
f
Server heup
C
I
i
e
n
f ob
j
e
c
f
CIient heup
2
Creofe cIienf ond server 'heIpers'. They'II hondIe oII
fhe Iow-IeveI nefworking ond I/O defoiIs so your cIienf
ond service con prefend Iike fhey're in fhe some heop.
S
e
r
v
ice o
b
j
e
c
f
Server heup
C
I
i
e
n
f ob
j
e
c
f
CIient heup
C
I
i
e
n
f he
Ip
e
r
S
e
r
v
ice h
e
I
p
e
r
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
612 chapter 18
Thc hclcis` aic ihc ol|ccis ihai aciually uo ihc communicaiing.
Thcy maIc ii ossillc loi ihc clicni io n as ihough iis calling a
mcihou on a local ol|cci. In laci, ii .. Thc clicni calls a mcihou on
ihc clicni hclci, n . Le I.er LeIe. we.e Le nunI e...e. TLe I.er
LeIe. . n .o:, o. Le FenI TL.r.
In oihci woius, ihc clicni ol|cci L.rI ii`s calling a mcihou on
ihc icmoic scivicc, lccausc ihc clicni hclci is .eerJ.r io lc
ihc scivicc ol|cci. Pretending to be the thing with the method the cIient
wonts to coII:
Bui ihc clicni hclci isn`i ically ihc icmoic scivicc. Alihough ihc
clicni hclci n liIc ii lccausc ii has ihc samc mcihou ihai ihc
scivicc is auvciiising), ihc clicni hclci uocsn`i havc any ol ihc
aciual mcihou logic ihc clicni is cxcciing. Insicau, ihc clicni
hclci coniacis ihc scivci, iianslcis inloimaiion aloui ihc mcihou
call c.g., namc ol ihc mcihou, aigumcnis, cic.), anu waiis loi a
iciuin liom ihc scivci.
On ihc scivci siuc, ihc scivicc hclci icccivcs ihc icqucsi liom
ihc clicni hclci ihiough a SocIci conncciion), unacIs ihc
inloimaiion aloui ihc call, anu ihcn invoIcs ihc .enI mcihou on
ihc .enI scivicc ol|cci. So io ihc scivicc ol|cci, ihc call is local. Ii`s
coming liom ihc scivicc hclci, noi a icmoic clicni.
Thc scivicc hclci gcis ihc iciuin valuc liom ihc scivicc, acIs ii
u, anu shis ii lacI ovci a SocIci`s ouiui siicam) io ihc clicni
hclci. Thc clicni hclci unacIs ihc inloimaiion anu iciuins ihc
valuc io ihc clicni ol|cci.
Ihc re|c ef !hc 'hc|pcrs
(a e]jn( je( g(, (
ze( ]j[ j(', z[jng (
([] ez]],. @a( w[z(
j(', z]]y ]jng j, ez]]jng
([], n z [z-]ez]
'yy' je( ([z( [zn]],
z]] ([ ]w-]v] ](zj], |
e[(, zn] ,(z,.
S
e
r
v
ice o
b
j
e
c
f
Server heup
C
I
i
e
n
f ob
j
e
c
f
CIient heup
C
I
i
e
n
f he
Ip
e
r
S
e
r
v
ice h
e
I
p
e
r
c|--l --:l l-:
l': l.|- l- l-
-.| --:- |l
l-: l- :|--l
-|-- : l- l-
l.l :.- .:l-.||]
- l- --.| ---
c|--l -|-- --l--:
l- - l- :--:-, -l
l': -:l . --] -- l-
-.| 1-
--:- -|-- -l: l-
----:l --- l- :|--l
-|--, --.:: l, .-
:.||: l- --l- -- l-
-.| --:-
1
- --:- --:l |
l-
-.| --:- |l': l-
--:l -
l l- -
-l-
l.l .:l-.||] --: l-
--.| -
-l- -
--
cIient and server heIpers
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 613
S
e
r
v
ice o
b
j
e
c
f
Server heup
C
I
i
e
n
f ob
j
e
c
f
CIient heup
C
I
i
e
n
f he
Ip
e
r
S
e
r
v
ice h
e
I
p
e
r
How the method call happens
1 CIienf objecf coIIs do8igThing() on fhe cIienf heIper objecf
S
e
r
v
ice o
b
j
e
c
f
Server heup
C
I
i
e
n
f ob
j
e
c
f
CIient heup
C
I
i
e
n
f he
Ip
e
r
S
e
r
v
ice h
e
I
p
e
r
2 CIienf heIper pockoges up informofion obouf fhe coII
(orgumenfs, mefhod nome, efc.) ond ships if over fhe
nefwork fo fhe service heIper.
do8igThing()
do8igThing()
"cIienf wonfs fo coII o mefhod"
S
e
r
v
ice o
b
j
e
c
f
Server heup
C
I
i
e
n
f ob
j
e
c
f
CIient heup
C
I
i
e
n
f he
Ip
e
r
S
e
r
v
ice h
e
I
p
e
r
3 Service heIper unpocks fhe informofion from fhe cIienf heIper,
fnds ouf which mefhod fo coII (ond on which objecf) ond
invokes fhe reoI mefhod on fhe reoI service objecf.
do8igThing()
"cIienf wonfs fo coII o mefhod"
do8igThing()
------, l: : l-
--:l -l l- !A|
--l- |-: 1- -]
l.l --: l- --.| ---'
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
614 chapter 18
In ]ava, RMI luilus ihc clicni anu scivicc hclci
ol|ccis loi you, anu ii cvcn Inows how io maIc ihc
clicni hclci looI liIc ihc Rcal Scivicc. In oihci
woius, RMI Inows how io givc ihc clicni hclci
ol|cci ihc samc mcihous you wani io call on ihc
icmoic scivicc.
Plus, RMI ioviucs all ihc iuniimc inliasiiuciuic io
maIc ii woiI, incluuing a looIu scivicc so ihai ihc
clicni can hnu anu gci ihc clicni hclci ihc ioxy
loi ihc Rcal Scivicc).
Wiih RMI, you uon`i wiiic nr, ol ihc nciwoiIing
oi I/O couc youiscll. Thc clicni gcis io call icmoic
mcihous i.c. ihc oncs ihc Rcal Scivicc has) |usi
liIc noimal mcihou calls on ol|ccis iunning in ihc
clicni`s own local ]VM.
Almosi.
Thcic is onc uillcicncc lciwccn RMI calls anu local
noimal) mcihou calls. Rcmcmlci ihai cvcn ihough
io ihc clicni ii looIs liIc ihc mcihou call is local,
ihc clicni hclci scnus ihc mcihou call acioss ihc
nciwoiI. So ihcic is nciwoiIing anu I/O. Anu whai
uo wc Inow aloui nciwoiIing anu I/O mcihous.
Thcy`ic iisIy!
Thcy ihiow cxcciions all ovci ihc lacc.
So, ihc clicni uocs havc io acInowlcugc ihc iisI. Thc
clicni has io acInowlcugc ihai whcn ii calls a icmoic
mcihou, cvcn ihough io ihc clicni ii`s |usi a local call
io ihc ioxy/hclci ol|cci, ihc call uI.neI, involvcs
SocIcis anu siicams. Thc clicni`s oiiginal call is IonI,
lui ihc ioxy iuins ii inio a .eoe call. A icmoic call
|usi mcans a mcihou ihai`s invoIcu on an ol|cci on
anoihci ]VM. How ihc inloimaiion aloui ihai call
gcis iianslciicu liom onc ]VM io anoihci uccnus
on ihc ioiocol uscu ly ihc hclci ol|ccis.
Wiih RMI, you havc a choicc ol ioiocols: ]RMP oi
IIOP. ]RMP is RMI`s naiivc` ioiocol, ihc onc mauc
|usi loi ]ava-io-]ava icmoic calls. IIOP, on ihc oihci
hanu, is ihc ioiocol loi CORBA Common Ol|cci
Rcqucsi BioIci Aichiicciuic), anu lcis you maIc
icmoic calls on ihings which aicn`i ncccssaiily ]ava
ol|ccis. CORBA is usually uL moic ainlul ihan
RMI, lccausc il you uon`i havc ]ava on loih cnus,
ihcic`s an awlul loi ol iianslaiion anu convcision ihai
has io hacn.
Bui ihanIlully, all wc caic aloui is ]ava-io-]ava, so
wc`ic siicIing wiih lain olu, icmaiIally casy RMI.
1zvz KM| ]| vcs yee !hc r||cn! zn4
scrv|rc hc|pcr e|jcr!s|
S
e
r
v
ice o
b
j
e
c
f
C
I
i
e
n
f ob
j
e
c
f
C
I
i
e
n
f he
Ip
e
r
S
e
r
v
ice h
e
I
p
e
r
Server heup
CIient heup
PMI STU
PMI SkELETON
n RM, the client helper is a stub'
and the server helper is a skeleton'.
RMI heIper objects
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 615
Server
Making the Remote 8ervice
Moke o Pemote Interfuce
Moke o Pemote ImpIementution
0enerofe fhe stubs ond skeIetons using rmic
Sforf fhe PMI registry (rmiregisfry)
Sforf fhe remote service
HyRemote.java
puo||c |rlerlace
VyRerole exlerds
Rerole {
HyRemote|mp|.java
puo||c |rlerlace
VyRerole exlerds
Rerole {
This is an ol ihc hvc sics loi maIing ihc icmoic
scivicc ihai iuns on ihc scivci). Don`i woiiy, cach sic is
cxlaincu in uciail ovci ihc ncxi lcw agcs.
Thc icmoic inicilacc uchncs ihc mcihous
ihai a clicni can call icmoicly. Ii`s whai
ihc clicni will usc as ihc olymoihic class
iyc loi youi scivicc. Boih ihc Siul anu
aciual scivicc will imlcmcni ihis!
1
: -l--.:- ---: l-
---
-l- -
-l-: l.l ]--
-
.-l :|--l: l- :.||
This is ihc class ihai uocs ihc Rcal WoiI.
Ii has ihc ical imlcmcniaiion ol ihc
icmoic mcihous uchncu in ihc icmoic
inicilacc. Ii`s ihc ol|cci ihai ihc clicni
wanis io call mcihous on.
1- -.| --:- 1- :|.::
-l l- --l-: l.l -
l- --.| --- |l -|----l:
l- ----l- -l--.:-
Thcsc aic ihc clicni anu scivci hclcis`.
You uon`i havc io cicaic ihcsc classcs oi cvci
looI ai ihc souicc couc ihai gcnciaics ihcm.
Ii`s all hanulcu auiomaiically whcn you
iun ihc imic iool ihai shis wiih youi ]ava
ucvclomcni Iii.
File Edit Window Help Eat
%rmic MyRemoteImpl
HyRemote|mp|_8tub.c|ass
HyRemote|mp|_8ke|.c|ass
---- --: ..-:l l- .:l-.|
:--:- -|----l.l-- :|.::
:l: --l l-- ---
:|.::-: -- l-
-|-- --:l:
File Edit Window Help Drink
%rmiregistry
File Edit Window Help BeMerry
%java MyRemoteImpl
Thc is liIc ihc whiic agcs ol a
honc looI. Ii`s whcic ihc usci gocs io gci
ihc ioxy ihc clicni siul/hclci ol|cci).
You havc io gci ihc scivicc ol|cci u anu iunning.
Youi scivicc imlcmcniaiion class insianiiaics an
insiancc ol ihc scivicc anu icgisicis ii wiih ihc RMI
icgisiiy. Rcgisiciing ii maIcs ihc scivicc availallc loi
clicnis.
--- l: - .
:-.-.l- l----.|
8tep one:
8tep two:
8tep three:
8tep four:
8tep hve:
101101
10 110 1
0 11 0
001 10
001 01
101101
10 110 1
0 11 0
001 10
001 01
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
616 chapter 18
8tep one: Make a Remote nterface
1 Etend juvu,rmi,Pemote
HyRemote.java
puo||c |rlerlace
VyRerole exlerds
Rerole {
Rcmoic is a maiIci` inicilacc, which mcans ii has no mcihous. Ii has
sccial mcaning loi RMI, ihough, so you musi lollow ihis iulc. Noiicc
ihai wc say cxicnus` hcic. Onc inicilacc is allowcu io anoihci
inicilacc.
public interface MyRemote extends Remote {
2 DecIore fhof oII mefhods throw u PemoteEception
Thc icmoic inicilacc is ihc onc ihc clicni uscs as ihc olymoihic iyc
loi ihc scivicc. In oihci woius, ihc clicni invoIcs mcihous on somcihing
ihai imlcmcnis ihc icmoic inicilacc. Thai somcihing is ihc siul, ol
couisc, anu sincc ihc siul is uoing nciwoiIing anu I/O, all Iinus ol Bau
Things can hacn. Thc clicni has io acInowlcugc ihc iisIs ly hanuling
oi ucclaiing ihc icmoic cxcciions. Il ihc mcihous in an inicilacc
ucclaic cxcciions, any couc calling mcihous on a iclcicncc ol ihai iyc
ihc inicilacc iyc) musi hanulc oi ucclaic ihc cxcciions.
import java.rmi.*;
public interface MyRemote extends Remote {
public String sayHello() throws RemoteException;
}
3 e sure urguments und return vuIues ure primitives or SeriuIizubIe
Aigumcnis anu iciuin valucs ol a icmoic mcihou musi lc ciihci iimiiivc
oi Sciializallc. ThinI aloui ii. Any aigumcni io a icmoic mcihou has io
lc acIagcu u anu shicu acioss ihc nciwoiI, anu ihai`s uonc ihiough
Sciializaiion. Samc ihing wiih iciuin valucs. Il you usc iimiiivcs, Siiings,
anu ihc ma|oiiiy ol iycs in ihc API incluuing aiiays anu collcciions),
you`ll lc hnc. Il you aic assing aiounu youi own iycs, |usi lc suic ihai
you maIc youi classcs imlcmcni Sciializallc.
public String sayHello() throws RemoteException;
/--- -l--.:- .: l-
.-----:- l.l l': --
----l- --l- :.||: A-
-l--.:- :.-'l -|----l
.-]l-, -l l :.- -l--
-l-- -l--.:-:
!--] ----l- --l- :.|| :
:--:--- '-:]' l-:|.--
---l-!:-l-- -- ---]
--l- --:-: l- :|--l
l- .] .ll--l-- .-
.:---|-- l.l l-:
-l --l ---
1: --l--- .|-- : ---. - :-
--- l- --- --- l- :---- .: l-
l- :|--l, :- l --:l - --.|-.|-
1.l': -- .-: .- --l--- .|--: -l
.:.- - .- :--l
l- ---l- -l--.:- : - ..--
a remote interface
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 617
8tep two: Make a Remote mplementation
1 ImpIement the Pemote interfuce
HyRemote|mp|.java
puo||c |rlerlace
VyRerole exlerds
Rerole {
Youi scivicc has io imlcmcni ihc icmoic inicilacc-ihc onc
wiih ihc mcihous youi clicni is going io call.
public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {
public String sayHello() {
return Server says, `Hey';
}
// more code in class
}
2 Etend UnicustPemoteObject
In oiuci io woiI as a icmoic scivicc ol|cci, youi ol|cci nccus somc
lunciionaliiy iclaicu io lcing icmoic`. Thc simlcsi way is io cxicnu
UnicasiRcmoicOl|cci liom ihc |ava.imi.scivci acIagc) anu lci ihai
class youi suciclass) uo ihc woiI loi you.
public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {
3 Write u no-urg constructor thut decIures u PemoteEception
Youi ncw suciclass, UnicasiRcmoicOl|cci, has onc liiilc iollcm-iis
consiiucioi ihiows a RcmoicExcciion. Thc only way io ucal wiih ihis is
io ucclaic a consiiucioi loi youi icmoic imlcmcniaiion, |usi so ihai you
havc a lacc io ucclaic ihc RcmoicExcciion. Rcmcmlci, whcn a class is
insianiiaicu, iis suciclass consiiucioi is always callcu. Il youi suciclass
consiiucioi ihiows an cxcciion, you havc no choicc lui io ucclaic ihai
youi consiiucioi also ihiows an cxcciion.
public MyRemoteImpl() throws RemoteException { }
4 Pegister the service with the PMI registry
Now ihai you`vc goi a icmoic scivicc, you havc io maIc ii availallc io
icmoic clicnis. You uo ihis ly insianiiaiing ii anu uiiing ii inio ihc RMI
icgisiiy which musi lc iunning oi ihis linc ol couc lails). Whcn you
icgisici ihc imlcmcniaiion ol|cci, ihc RMI sysicm aciually uis ihc in
ihc icgisiiy, sincc ihai`s whai ihc clicni ically nccus. Rcgisici youi scivicc
using ihc siaiic iclinu) mcihou ol ihc |ava.imi.Naming class.
try {
MyRemote service = new MyRemoteImpl();
Naming.rebind(Remote Hello, service);
} catch(Exception ex) {...}
1- :--|-- -|| -.- :--- l.l
]--'- -|----l- .|| l- --l-:
--- l- -l--.:- ]-- -|----l |-
l: :.:-, l---': --|] ---
/-- --'l .- l- -l .-]l- -
l- :--:l--:l-- /-- -:l --- .
-.] l- -:|.-- l.l ]--- :---:|.::
:--:l--:l-- l---: .- -:-l--
6- ]--- :--:- . -.-- |l.l :|--l: :.- -:-
l- |-- l - - l- --:l-]` .- --:l-- l
-l l- M| --:l-] w-- ]-- - l-
:--:- --:l, M| :-.: l- :--:- -- l-
:l- .- -l: l- :l- - l- --:l-]
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
618 chapter 18
8tep three: generate stubs and skeletons
1 Pun rmic on the remote impIementution cIuss
{not the remote interfuce}
Thc imic iool, ihai comcs wiih ihc ]ava soliwaic
ucvclomcni Iii, iaIcs a scivicc imlcmcniaiion anu
cicaics iwo ncw classcs, ihc siul anu ihc sIclcion.
Ii uscs a naming convcniion ihai is ihc namc ol
youi icmoic imlcmcniaiion, wiih ciihci _Siul oi
_SIclcion auucu io ihc cnu. Thcic aic oihci oiions
wiih imic, incluuing noi gcnciaiing sIclcions,
sccing whai ihc souicc couc loi ihcsc classcs looIcu
liIc, anu cvcn using IIOP as ihc ioiocol. Thc way
wc`ic uoing ii hcic is ihc way you`ll usually uo ii.
Thc classcs will lanu in ihc cuiicni uiiccioiy i.c.
whaicvci you uiu a cu io). Rcmcmlci, musi
lc allc io scc youi imlcmcniaiion class, so you`ll
iolally iun imic liom ihc uiiccioiy whcic youi
icmoic imlcmcniaiion is. Wc`ic uclilciaicly noi
using acIagcs hcic, io maIc ii simlci. In ihc Rcal
Woilu, you`ll nccu io accouni loi acIagc uiiccioiy
siiuciuics anu lully-qualihcu namcs).
%rmic MyRemoteImpl
HyRemote|mp|_8tub.c|ass
HyRemote|mp|_8ke|.c|ass
N-l:- l.l ]-- --'l :.] :|.::'
-- l- -- )-:l l- :|.:: -.--
:l: --l l-- ---
:|.::-: -- l-
-|-- --:l:
8tep four: run rmiregistry
1 ring up u terminuI und sturt the rmiregistry,
Bc suic you siaii ii liom a uiiccioiy ihai has acccss
io youi classcs. Thc simlcsi way is io siaii ii liom
youi classcs` uiiccioiy.
File Edit Window Help Huh?
%rmiregistry
File Edit Window Help Whuffe
8tep hve: start the service
1 ring up unother terminuI und sturt your service
This mighi lc liom a main) mcihou in youi icmoic
imlcmcniaiion class, oi liom a scaiaic launchci class.
In ihis simlc cxamlc, wc ui ihc siaiici couc in ihc
imlcmcniaiion class, in a main mcihou ihai insianiiaics
ihc ol|cci anu icgisicis ii wiih RMI icgisiiy.
File Edit Window Help Huh?
%java MyRemoteImpl
101101
10 110 1
0 11 0
001 10
001 01
101101
10 110 1
0 11 0
001 10
001 01
stubs and skeIetons
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 619
Complete code for the server side
import java.rmi.*;
import java.rmi.server.*;
public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {
public String sayHello() {
return Server says, `Hey';
}
public MyRemoteImpl() throws RemoteException { }
public static void main (String[] args) {
try {
MyRemote service = new MyRemoteImpl();
Naming.rebind(Remote Hello, service);
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
import java.rmi.*;
public interface MyRemote extends Remote {
public String sayHello() throws RemoteException;
}
---l-!:-l-- .- ---l-
-l--.:- .-- - ..-- .:.-
/--- -l--.:- Mc1 -l--
..-----l-
A|| - ]--- ----l- --l-: --:l
-:|.-- . ---l-!:-l--
c
-:.:l---l-6-:l : - l-
..--:---- .:.-
The Remote interface:
The Remote service {the implementation}:
-l--- c-:.:l---l-6-:l : l-
-.:-:l -.] l- -.- . ----l- --:l
]-- Mc1 -|----l ]--- ----l- -l--.:-''
/-- .- l- -|----l .|| l-
-l--.:- --l-:, - :---:- B-l
--l:- l.l ]-- - N61 .- l-
-:|.-- l- ---l-!:-l--
]--- :---:|.:: :--:l--:l-- |--
c-:.:l---l-6-:l` -:|.--: .- -:-l--, :-
/6c --:l --l- . :--:l--:l--, -:.-:- l --.-:
l.l ]--- :--:l--:l-- : :.||- -:] :-- |l:
:--- :--:l--:l--`
M.- l- ----l- --:l, l-- '-' l l- l-
----:l-] -:- l- :l.l: N.--,---|` 1-
-.-- ]-- --:l-- l ---- : l- -.-- :|--l: -||
--- l- |-- l - - l- -- --:l-]
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
620 chapter 18
Hew 4ecs !hc r||cn! ]c! !hc s!e| e|jcr!!
Thc clicni has io gci ihc siul ol|cci, sincc ihai`s ihc ihing ihc
clicni will call mcihous on. Anu ihai`s whcic ihc RMI icgisiiy
comcs in. Thc clicni uocs a looIu`, liIc going io ihc whiic agcs
ol a honc looI, anu csscniially says, Hcic`s a namc, anu I`u liIc
ihc siul ihai gocs wiih ihai namc."
MyRemote service = (MyRemote) Naming.lookup(rmi://127.0.0.1/Remote Hello);
1- :|--l .|-.]: -:-: l-
----l- -|----l.l-- .: l-
l]- - l- :--:- |- .:l,
l- :|--l ---- ---: l- ---
l- .:l-.| :|.:: -.-- - ]---
----l- :--:-
/-- .- l- :.:l l l- l-
-l--.:-, :-:- l- |---
--l- --l---: l]- 6-:l
|---|` : . :l.l: --l- -
l- N.-- :|.::
]--- -:l -.-- -- ||
.--:: --: ---
1: --:l - l- -.--
l.l l- :--:- -.:
--:l--- ----
S
e
r
v
ice o
b
j
e
c
f
C
I
i
e
n
f ob
j
e
c
f
Sfub
S
k
eIefo
n
Server
CIient
Stub
PMI registry {on server}
1 CIient does u Iookup on the PMI registry
2 PMI registry returns the stub object
as ihc iciuin valuc ol ihc looIu mcihou) anu RMI
ucsciializcs ihc siul auiomaiically. You MUST havc
ihc siul class ihai imic gcnciaicu loi you) on ihc
clicni oi ihc siul won`i lc ucsciializcu
3 CIient invokes u method on the stub us
though the stub IS the reuI service
1
2
3
Naming.lookup(rmi://127.0.0.1/Remote Hello);
I
o
o
k
u
p
(
)
s
f
u
b
r
e
f
u
r
n
e
d
so
y
H
e
IIo
( )
getting the stub
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 621
Hew 4ecs !hc r||cn! ]c! !hc s!e| r|zss!
Now wc gci io ihc inicicsiing qucsiion. Somchow, somcway, ihc
clicni musi havc ihc siul class ihai you gcnciaicu cailici using
imic) ai ihc iimc ihc clicni uocs ihc looIu, oi clsc ihc siul won`i
lc ucsciializcu on ihc clicni anu ihc wholc ihing llows u. In a
simlc sysicm, you can simly hanu-uclivci ihc siul class io ihc
clicni.
Thcic`s a much coolci way, ihough, alihough ii`s lcyonu ihc
scoc ol ihis looI. Bui |usi in casc you`ic inicicsicu, ihc coolci
way is callcu uynamic class uownloauing". Wiih uynamic class
uownloauing, a siul ol|cci oi ically any Sciializcu ol|cci) is
siamcu` wiih a URI ihai iclls ihc RMI sysicm on ihc clicni
whcic io hnu ihc class hlc loi ihai ol|cci. Thcn, in ihc ioccss ol
ucsciializing an ol|cci, il RMI can`i hnu ihc class locally, ii uscs
ihai URI io uo an HTTP Gci io iciiicvc ihc class hlc. So you`u
nccu a simlc Wcl scivci io scivc u class hlcs, anu you`u also
nccu io changc somc sccuiiiy aiamcicis on ihc clicni. Thcic aic
a lcw oihci iiicIy issucs wiih uynamic class uownloauing, lui ihai`s
ihc ovcivicw.
import java.rmi.*;
public class MyRemoteClient {
public static void main (String[] args) {
new MyRemoteClient().go();
}
public void go() {
try {
MyRemote service = (MyRemote) Naming.lookup(rmi://127.0.0.1/Remote Hello);
String s = service.sayHello();
System.out.println(s);
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
Complete client code
1- N.-- :|.:: |-- -- l-
-----:l-] |---` : - l-
..-- .:.-
|l :---: --l - l- --:l-] .: l]-
6-:l, :- --'l ---l l- :.:l
]-- --- l- || .--::
-- -:l-.--
.- l- -.-- -:- l-
-/--- l- :--:-
|l |--: -:l |- . ---|.- -| --l- :.||' |!:-l l --:l .:---|-- l- ---l-!:-l--`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
622 chapter 18
Bc serc czrh mzrh|nc hzs !hc r|zss
f||cs | ! ncc4s.
Thc io ihicc ihings iogiammcis uo wiong wiih RMI aic:
1) Ioigci io siaii imiicgisiiy lcloic siaiiing icmoic scivicc
whcn you icgisici ihc scivicc using Naming.iclinu), ihc
imiicgisiiy musi lc iunning!)
2) Ioigci io maIc aigumcnis anu iciuin iycs sciializallc
you won`i Inow uniil iuniimc, ihis is noi somcihing ihc
comilci will ucicci.)
S) Ioigci io givc ihc siul class io ihc clicni.
S
e
r
v
ice o
b
j
e
c
f
C
I
i
e
n
f ob
j
e
c
f
Sfub
S
k
eIefo
n
Server
CIient
HyRemote|mp|_8tub.c|ass
6||ent.c|ass
HyRemote|mp|_8tub.c|ass
Sfub
HyRemote.c|ass
HyRemote.c|ass
HyRemote|mp|.c|ass
HyRemote|mp|_8ke|.c|ass
l--'l ---l, l- :|--l
-:-: l- -l--.:- l- :.||
--l-: -- l- :l- 1-
:|--l )/M ---: l- :l-
:|.::, -l l- :|--l ----
----: l- l- :l- :|.::
- :-- 1- :|--l .|-.]:
-:-: l- ----l- -l--.:-,
.: l-- l- ----l-
-l--.:- w!! l-
.:l-.| ----l- --:l
---- ---: -l l- l- .- -|-l--
:|.::-:, .: --|| .: l- :--:- .- l-
----l- -l--.:- |l ---: l- :l- :|.::
-:.-:- -------, l- :l- : :-:ll-l-
-- l- --.| :--:-, --- l- --.| :--:-
: --- l- l- M| --:l-]
RMI cIass fiIes
1
- ---
-l- -l--.:-
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 623
yg'z
]j;z/
l.
2.
3.
4.
5.
6.
7.
Look at the sequence of events below, and
place them in the order in which they
occur in a 1ava PM| application.
T|e RVl re|slry |s slarled
T|e rerole serv|ce (rerole
|rp|ererlal|or) |s |rslarl|aled
T|e c||erl does a |oo|up or
l|e RVl Re|slry
T|e sluo serds l|e rel|od
ca|| lo l|e server
T|e c||erl |rvo|es a rel|od
or l|e sluo
T|e c||erl els l|e sluo lror
l|e RVl re|slry
T|e rerole serv|ce |s re|s-
lered W|l| l|e RVl re|slry
+,-+ :+ ,-+:.|
8ll P0lk5
Ar oojecl or ore |eap carrol el a rorra| Java
relererce lo ar oojecl or a d|llererl |eap (W||c| rears
rurr|r or a d|llererl JvV)
Java Rerole Vel|od lrvocal|or (RVl) ra|es |l seem |||e
you're ca|||r a rel|od or a rerole oojecl (|.e. ar oojecl
|r a d|llererl JvV), oul you arer'l.
w|er a c||erl ca||s a rel|od or a rerole oojecl, l|e
c||erl |s rea||y ca|||r a rel|od or a roxy ol l|e rerole
oojecl. T|e proxy |s ca||ed a 'sluo'.
A sluo |s a c||erl |e|per oojecl l|al la|es care ol l|e |oW-
|eve| relWor||r dela||s (soc|els, slrears, ser|a||zal|or,
elc.) oy pac|a|r ard serd|r rel|od ca||s lo l|e
server.
To ou||d a rerole serv|ce (|r ol|er Words, ar oojecl l|al
a rerole c||erl car u|l|rale|y ca|| rel|ods or), you rusl
slarl W|l| a rerole |rlerlace.
A rerole |rlerlace rusl exlerd l|e java.rr|.Rerole
|rlerlace, ard a|| rel|ods rusl dec|are
ReroleExcepl|or.
Your rerole serv|ce |rp|ererls your rerole |rlerlace.
Your rerole serv|ce s|ou|d exlerd ur|caslRerole0ojecl.
(Tec|r|ca||y l|ere are ol|er Ways lo creale a rerole oo-
jecl, oul exlerd|r ur|caslRerole0ojecl |s l|e s|rp|esl).
Your rerole serv|ce c|ass rusl |ave a corslruclor,
ard l|e corslruclor rusl dec|are a ReroleExcepl|or
(oecause l|e superc|ass corslruclor dec|ares ore).
Your rerole serv|ce rusl oe |rslarl|aled, ard l|e oojecl
re|slered W|l| l|e RVl re|slry.
To re|sler a rerole serv|ce, use l|e slal|c
Nar|r.reo|rd('3erv|ce Nare, serv|celrslarce),
T|e RVl re|slry rusl oe rurr|r or l|e sare rac||re
as l|e rerole serv|ce, oelore you lry lo re|sler a rerole
oojecl W|l| l|e RVl re|slry.
T|e c||erl |oo|s up your rerole serv|ce us|r l|e slal|c
Nar|r.|oo|up('rr|://VyloslNare/3erv|ceNare),
A|rosl everyl||r re|aled lo RVl car l|roW a
ReroleExcepl|or (c|ec|ed oy l|e corp||er). T||s
|rc|udes re|sler|r or |oo||r up a serv|ce |r l|e re|slry,
ard a|| rerole rel|od ca||s lror l|e c||erl lo l|e sluo.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
624 chapter 18
Yczh, |e! whe rcz||y escs KM|!
I use if
for serious 8-fo-8,
e-commerce bock-
ends, running on JZEE
fechnoIogy.
We use if
for our cooI
new decision-supporf
sysfem.
I heord your ex-
wife sfiII uses
pIoin sockefs.
We've gof on
EJ8-bosed hofeI
reservofion sysfem.
And EJ8 uses PMIl
I jusf con'f imogine
Iife wifhouf our Jini-
enobIed home nefwork
ond oppIiconces.
Me fool How
did onyone gef
by7 I jusf Iove PMI
for giving us Jini
fechnoIogy.
uses for RMI
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 625
Thonks
Ko|hy
5ierro
obs
Pe|s
Kathy
Sierra
Whz! z|ee! 8crv|c!s!
Scivlcis aic ]ava iogiams ihai iun on anu wiih) an HTTP wcl scivci. Whcn a clicni uscs a
wcl liowsci io iniciaci wiih a wcl agc, a icqucsi is scni lacI io ihc wcl scivci. Il ihc icqucsi
nccus ihc hcl ol a ]ava scivlci, ihc wcl scivci iuns oi calls, il ihc scivlci is alicauy iunning)
ihc scivlci couc. Scivlci couc is simly couc ihai iuns on ihc scivci, io uo woiI as a icsuli ol
whaicvci ihc clicni icqucsis loi cxamlc, savc inloimaiion io a icxi hlc oi uaialasc on ihc
scivci). Il you`ic lamiliai wiih CGI sciiis wiiiicn in Pcil, you Inow cxacily whai wc`ic ialIing
aloui. Wcl ucvclocis usc CGI sciiis oi scivlcis io uo cvciyihing liom scnuing usci-sulmiiicu
inlo io a uaialasc, io iunning a wcl-siic`s uiscussion loaiu.
ArJ e.er e..Ie nr ue FAI
By lai, ihc mosi common usc ol ]2EE icchnology is io mix scivlcis anu E]Bs iogcihci, whcic
scivlcis aic ihc clicni ol ihc E]B. Anu in ihai casc, Le e..Ie . u.r FAI o nII o Le EJB.
Alihough ihc way you usc RMI wiih E]B is a I.Ie uillcicni liom ihc ioccss wc |usi looIcu ai.)
101101
10 110 1
0 11 0
001 10
001 01
Hy8erv|et.c|ass
Web Server
Web rowser
{cIient}
"cIienf requesfs PegisferServIef"
1
CIienf fIIs ouf o regisfrofion form ond cIicks 'submif'.
The HTTP server (i.e. web server) gefs fhe requesf, sees fhof
if's for o servIef, ond sends fhe requesf fo fhe servIef.
101101
10 110 1
0 11 0
001 10
001 01
Hy8erv|et.c|ass
Web Server
Web rowser
{cIient}
"cIienf requesfs PegisferServIef"
2
ServIef (Jovo code) runs, odds dofo fo fhe dofobose,
composes o web poge (wifh cusfom info) ond sends if bock fo
fhe cIienf where if dispIoys in fhe browser.
conf|rm.htm|
<HTML>
<BODY>
Java
rules!
<BODY>
<HTML>
"here's o confrmofion poge"
100% LocuI Combinution 100% Pemote
8erv|ets
HTTP
web 8tart
FiIe Edit View
HTTP
RH| app
FiIe Edit View
RMI
Executab|e
Jar
FiIe Edit View
8erv|ets
HTTP
8erv|ets
HTTP
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
626 chapter 18
very simpIe servIet
8tep for making and running a servlet
1 Find out where your servIets need to be pIuced,
Ioi ihcsc cxamlcs, wc`ll assumc ihai you alicauy havc a wcl scivci
u anu iunning, anu ihai ii`s alicauy conhguicu io suoii scivlcis.
Thc mosi imoiiani ihing is io hnu oui cxacily whcic youi scivlci
class hlcs havc io lc laccu in oiuci loi youi scivci io scc` ihcm. Il
you havc a wcl siic hosicu ly an ISP, ihc hosiing scivicc can icll you
whcic io ui youi scivlcis, |usi as ihcy`ll icll you whcic io lacc youi
CGI sciiis.
101101
10 110 1
0 11 0
001 10
001 01
Hy8erv|etA.c|ass
Web Server
8erv|ets
2 Set the servIets,jur und udd it to your cIussputh
Scivlcis aicn`i aii ol ihc sianuaiu ]ava liliaiics, you nccu
ihc scivlcis classcs acIagcu inio ihc scivlcis.|ai hlc. You can
uownloau ihc scivlcis classcs liom |ava.sun.com, oi you can gci
ihcm liom youi ]ava-cnallcu wcl scivci liIc Aachc Tomcai, ai
ihc aachc.oig siic). Wiihoui ihcsc classcs, you won`i lc allc io
comilc youi scivlcis.
3 Write u servIet cIuss by etending HttpServIet
A scivlci is |usi a ]ava class ihai cxicnus HiiScivlci liom ihc
|avax.scivlci.hii acIagc). Thcic aic oihci iycs ol scivlcis you
can maIc, lui mosi ol ihc iimc wc caic only aloui HiiScivlci.
public class MyServletA extends HttpServlet { ... }
serv|ets.jar
4 Write un HTML puge thut invokes your servIet
Whcn ihc usci clicIs a linI ihai iclcicnccs youi scivlci, ihc wcl
scivci will hnu ihc scivlci anu invoIc ihc aioiiaic mcihou
uccnuing on ihc HTTP commanu GET, POST, cic.)
<a href=servlets/MyServletA>This is the most amazing servlet.</a>
5 Muke your servIet und HTML puge uvuiIubIe to your server
This is comlcicly uccnucni on youi wcl scivci anu moic sccih-
cally, on which ol ]ava Scivlcis ihai you`ic using). Youi ISP
may simly icll you io uio ii inio a Scivlcis" uiiccioiy on youi
wcl siic. Bui il you`ic using, say, ihc laicsi vcision ol Tomcai, you`ll
havc a loi moic woiI io uo io gci ihc scivlci anu wcl agc) inio
ihc iighi locaiion. Wc |usi hacn io havc a looI on ihis ioo .)
101101
10 110 1
0 11 0
001 10
001 01
Hy8erv|etA.c|ass
HyPage.htm|
<HTML>
<BODY>
Java
rules!
<BODY>
<HTML>
101101
10 110 1
0 11 0
001 10
001 01
Hy8erv|etA.c|ass
Web Server
8erv|ets
HyPage.htm|
<HTML>
<BODY>
Java
rules!
<BODY>
<HTML>
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 627
vcry s|mp|c 8crv|c!
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServletA extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(text/html);
PrintWriter out = response.getWriter();
String message = If you're reading this, it worked!;
out.println(<HTML><BODY>);
out.println(<H1> + message + </H1>);
out.println(</BODY></HTML>);
out.close();
}
}
B-:-: -, -- --- l- ---l l-- - l- :--|-l .:.-:
------, l-:- l-- .:.-: .-- N61 .-l - l- )..
:l.-.- |-.--: ~~ ]-- .- l- ---|-. l-- :-.-.l-|]
M-:l '----.|' :--|-l: -|| -l--
+ll--|-l, l-- ----- --- --
---- --l-:
6---- l- -6-l -- :-|-
+11| 6!1 --::.-:
1- -- :---- :.||: l: --l-, .-- ]-- l- :|--l':
----:l |]-- :.- -l .l. --l - l` .- . '--:--:-'
--:l l.l ]--'|| -:- l- :-- .: . --:--:- |. .-`
1: l-||: l- :---- |.- ---:--` -.l - -
'l-' : :--- .: --- l- :---- .: . ---:|l -
l: :--|-l -----
1- --:--:- --:l -: -: .- --l-l :l--.- l-
'--l-' ----.l-- .: --l l- l- :----
w.l -- '--l-' : .- +1M| .-' 1- .-
-l: -|--- l--- l- :---- .: l-
l- ---:--, -:l |- .-] -l-- +1M| .-,
--- l-- l: : . .- l.l ---- -:l-
--l| --- |- -l-- ---:, l---': -- l-| |-
:------- -l l: :l- - l
<HTML>
<BODY>
<a href=servlets/MyServletA>This is an amazing servlet.</a>
</BODY>
</HTML>
HIMI pz]c w| !h z ||nk !e !h|s scrv|c!
T||s ar araz|r serv|el.
w.l l- -- .- |--: |-
:|: l- |-
l- l--- l-
:--|-l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
628 chapter 18
(-,- a,- |
oa|| qa--(:|-
What's a 1SP, and how does it reIate to servIets!
1SP stands for 1ava Server Pages. |n the end, the web server
turns a 1SP into a servlet, but the difference between a servlet and
a 1SP is what OU (the developer) actually create. with a servlet,
you write a 1ava closs that contains l7Vl in the output statements
(if you're sending back an HTML page to the client). 8ut with a
1SP, it's the oppositeyou write an l7Vl page that contains 1ovo
code!
This gives you the ability to have dynamic web pages where you
write the page as a normal HTML page, except you embed 1ava
code (and other tags that "trigger 1ava code at runtime) that
gets processed at runtime. |n other words, part of the page is
customized at runtime when the 1ava code runs.
The main benefit of 1SP over regular servlets is that it's |ust a lot
easier to write the HTML part of a servlet as a 1SP page than to
write HTML in the torturous print out statements in the servlet's
response. |magine a reasonably complex HTML page, and now
imagine formatting it within println statements. ikes!
8ut for many applications, it isn't necessary to use 1SPs because
the servlet doesn't need to send a dynamic response, or the
HTML is simple enough not to be such a big pain. And, there are
still many web servers out there that support servlets but do not
support 1SPs, so you're stuck.
Another benefit of 1SPs is that you can separate the work by
having the 1ava developers write the servlets and the web page
developers write the 1SPs. That's the promised benefit, anyway.
|n reality, there's still a 1ava learning curve (and a tag learning
curve) for anyone writing a 1SP, so to think that an HTML web page
designer can bang out 1SPs is not realistic. well, not without tools.
8ut that's the good newsauthoring tools are starting to appear,
that help web page designers create 1SPs without writing the
code from scratch.
Is this aII you're gonna say about servIets! After such a
thing on RMI!
es. PM| is part of the 1ava language, and all the classes for
PM| are in the standard libraries. Servlets and 1SPs are not part of
the 1ava language, they're considered stonJotJ extens|ons. ou
can run PM| on any modern 1vM, but Servlets and 1SPs require a
properly configured web server with a servlet "container. This is
our way of saying, "it's beyond the scope of this book. 8ut you can
read much more in the lovely leoJ l|tst 5etvlets 8 15P.
8ll P0lk5
3erv|els are Java c|asses l|al rur erl|re|y or
(ard/or W|l||r) ar lTTP (Weo) server.
3erv|els are uselu| lor rurr|r code or l|e
server as a resu|l ol c||erl |rleracl|or W|l| a
Weo pae. For exarp|e, |l a c||erl suor|ls
|rlorral|or |r a Weo pae lorr, l|e serv|el car
process l|e |rlorral|or, add |l lo a dalaoase,
ard serd oac| a cuslor|zed, corl|rral|or
resporse pae.
To corp||e a serv|el, you reed l|e serv|el
pac|aes W||c| are |r l|e serv|els.jar l||e. T|e
serv|el c|asses are rol parl ol l|e Java slardard
||orar|es, so you reed lo doWr|oad l|e serv|els.
jar lror java.sur.cor or el l|er lror a serv|el-
capao|e Weo server. (Nole: l|e 3erv|el ||orary
|s |rc|uded W|l| l|e Java 2 Erlerpr|se Ed|l|or
(J2EE))
To rur a serv|el, you rusl |ave a Weo server
capao|e ol rurr|r serv|els, suc| as l|e Torcal
server lror apac|e.or.
Your serv|el rusl oe p|aced |r a |ocal|or l|al's
spec|l|c lo your parl|cu|ar Weo server, so you'||
reed lo l|rd l|al oul oelore you lry lo rur your
serv|els. ll you |ave a Weo s|le |osled oy ar l3P
l|al supporls serv|els, l|e l3P W||| le|| you W||c|
d|reclory lo p|ace your serv|els |r.
A lyp|ca| serv|el exlerds lllp3erv|el ard
overr|des ore or rore serv|el rel|ods, suc| as
do0el() or doPosl().
T|e Weo server slarls l|e serv|el ard ca||s l|e
appropr|ale rel|od (do0el(), elc.) oased or l|e
c||erl's requesl.
T|e serv|el car serd oac| a resporse oy ell|r
a Pr|rlwr|ler oulpul slrear lror l|e resporse
parareler ol l|e do0el() rel|od.
T|e serv|el 'Wr|les' oul ar lTVL pae, corp|ele
W|l| las).
servIets and JSP
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 629
1es! fer fen, |c!s mzkc !hc |hrzsc-0-Mz!|r
werk zs z scrv|c!
Now ihai wc iolu you ihai wc won`i
say any moic aloui scivlcis, wc can`i
icsisi scivlciizing ycs, wc vcilily
ii) ihc Phiasc-O-Maiic liom chaici 1.
A scivlci is siill |usi ]ava. Anu ]ava couc
can call ]ava couc liom oihci classcs.
So a scivlci is licc io call a mcihou on
ihc Phiasc-O-Maiic. All you havc io uo
is uio ihc Phiasc-O-Maiic class inio
ihc samc uiiccioiy as youi scivlci, anu
you`ic in lusincss. Thc Phiasc-O-
Maiic couc is on ihc ncxi agc).
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class KathyServlet extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String title = PhraseOMatic has generated the following phrase.;
response.setContentType(text/html);
PrintWriter out = response.getWriter();
out.println(<HTML><HEAD><TITLE>);
out.println(PhraseOmatic);
out.println(</TITLE></HEAD><BODY>);
out.println(<H1> + title + </H1>);
out.println(<P> + PhraseOMatic.makePhrase());
out.println(<P><a href=\KathyServlet\>make another phrase</a></p>);
out.println(</BODY></HTML>);
out.close();
}
}
Try my
new web-enobIed
phrose-o-mofic ond you'II
be o sIick foIker jusf Iike
fhe boss or fhose guys in
morkefing.
-- /--- :--|-l :.- :.|| --l-: --
.--l-- :|.:: |- l: :.:-, --'-- :.||-
l- :l.l: -.-|-.:-|` --l- - l-
|-.:-6M.l: :|.:: |-- l- --l .-`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
630 chapter 18
public class PhraseOMatic {
public static String makePhrase() {
// make three sets of words to choose from
String[] wordListOne = {24/7,multi-Tier,30,000 foot,B-to-B,win-win,front-
end, web-based,pervasive, smart, six-sigma,critical-path, dynamic};
String[] wordListTwo = {empowered, sticky, valued-added, oriented, centric,
distributed, clustered, branded,outside-the-box, positioned, networked, fo-
cused, leveraged, aligned, targeted, shared, cooperative, accelerated};
String[] wordListThree = {process, tipping point, solution, architecture,
core competency, strategy, mindshare, portal, space, vision, paradigm, mis-
sion};
// nd out how many words are in each list
int oneLength = wordListOne.length;
int twoLength = wordListTwo.length;
int threeLength = wordListThree.length;
// generate three random numbers, to pull random words from each list
int rand1 = (int) (Math.random() * oneLength);
int rand2 = (int) (Math.random() * twoLength);
int rand3 = (int) (Math.random() * threeLength);
// now build a phrase
String phrase = wordListOne[rand1] + + wordListTwo[rand2] + +
wordListThree[rand3];
// now return it
return (What we need is a + phrase);
}
}
|hrzsc-0-Mz!|r re4c, scrv|c!-fr|cn4|y
This is a slighily uillcicni vcision liom ihc couc in chaici onc. In ihc
oiiginal, wc ian ihc cniiic ihing in a main) mcihou, anu wc hau io iciun
ihc iogiam cach iimc io gcnciaic a ncw hiasc ai ihc commanu-linc. In ihis
vcision, ihc couc simly iciuins a Siiing wiih ihc hiasc) whcn you invoIc
ihc siaiic maIcPhiasc) mcihou. Thai way, you can call ihc mcihou liom any
oihci couc anu gci lacI a Siiing wiih ihc ianuomly-comoscu hiasc.
Plcasc noic ihai ihcsc long Siiing]| aiiay assignmcnis aic a viciim ol woiu-
ioccssing hcic-uon`i iyc in ihc hyhcns! ]usi Icc on iying anu lci youi
couc cuiioi uo ihc wiaing. Anu whaicvci you uo, uon`i hii ihc iciuin Icy in
ihc miuulc ol a Siiing i.c. somcihing lciwccn uoullc quoics).
Phrase-O-Matic code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 631
In!crpr|sc 1zvzBczns: KM| en s!cre|4s
RMI is gicai loi wiiiing anu iunning icmoic sciviccs. Bui
you woulun`i iun somcihing liIc an Amazon oi cBay on RMI
alonc. Ioi a laigc, ucauly sciious, cniciiisc alicaiion, you
nccu somcihing moic. You nccu somcihing ihai can hanulc
iiansaciions, hcavy concuiicncy issucs liIc a gazillion
colc aic hiiiing youi scivci ai oncc io luy ihosc oiganic
uog Iilllcs), sccuiiiy noi |usi anyonc shoulu hii youi
ayioll uaialasc), anu uaia managcmcni. Ioi ihai, you nccu
an ere...e nI.n.or e..e..
In ]ava, ihai mcans a ]ava 2 Eniciiisc Euiiion ]2EE) scivci.
A ]2EE scivci incluucs loih a wcl scivci anu an Eniciiisc
]avaBcansE]B) scivci, so ihai you can ucloy an alicaiion
ihai incluucs loih scivlcis anu E]Bs. IiIc scivlcis, E]B is
way lcyonu ihc scoc ol ihis looI, anu ihcic`s no way io
show |usi a liiilc" E]B cxamlc wiih couc, lui wc w.II iaIc
a quicI looI ai how ii woiIs. Ioi a much moic uciailcu
iicaimcni ol E]B, wc can iccommcnu ihc livcly Hcau Iiisi
E]B cciiihcaiion siuuy guiuc.)
E
J
8
obje
c
f
C
I
i
e
n
f ob
j
e
c
f
C
I
i
e
n
f he
Ip
e
r
S
e
r
v
ice h
e
I
p
e
r
CIient
PMI STU
PMI SkELETON
1: :|--l :--| - AN/1+|N6, -l
l]:.||] .- !)B :|--l : . :--|-l
----- - l- :.-- )i!! :----
e
n
f
e
r
pris
e
b
e
o
n
+---': ---- l- !)B :---- -l:
--|-' 1- !)B --:l -l--:-l:
l- :.||: l- l- -.- |l- -.- -|:
l- --.| -:--:: |-:` .- |.]--: -
.|| l- :--:-: --- ] l- !)B
:---- |:-:--l], l-.-:.:l--:, -l:`
EJ server
1- -.- --:l : --l-:l- ---
--:l :|--l .::-::' 6-|] l- :----
:.- .:l-.||] l.| l- l- -.- 1:
|-l: l- :---- - l-: |- :.],
w-.' 1: :|--l --:-'l .-
l- :-:--l] :|-.-.-:- l- :.|| l:
--l-' A|--:l ---]l- ]-- .]
-- - .- !)B :---- .--: -l
+!!, ---- l- :---- :l-: -'
D
jn []@ ,v z]], z ane[
| ,vje, ([z( ya ]n'( g(
wj([ ,(zjg[( p]. [[jng,
]j[ (zn,ze(jn,, ,eaj(y,
eneaney, ]z(zz,
znzgn(, zn] n(w[jng.
jn []@ ,v ,(, jn( ([
j]]] | zn p] ez]] zn]
]zy, jn z]] | ([ ,vje,.
This is onIy o smoII porf of fhe EJ8 picfurel
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
632 chapter 18
Ier eer f|nz| !r|rk... z || !!|c 1|n|
Wc lovc ]ini. Wc ihinI ]ini is iciiy much ihc lcsi ihing in ]ava. Il E]B is RMI
on sicioius wiih a lunch ol managcis), ]ini is RMI wiih w.r. Puic ]ava bI..
IiIc ihc E]B maiciial, wc can`i gci inio any ol ihc ]ini uciails hcic, lui il you
Inow RMI, you`ic ihicc-quaiicis ol ihc way ihcic. In icims ol icchnology,
anyway. In icims ol .rJe, ii`s iimc io maIc a lig lca. No, ii`s iimc io ,.
]ini uscs RMI alihough oihci ioiocols can lc involvcu), lui givcs you a lcw
Icy lcaiuics incluuing:
Adoptive discovery
SeI[-heoIing networhs
Wiih RMI, icmcmlci, ihc clicni has io Inow ihc
namc anu locaiion ol ihc icmoic scivicc. Thc
clicni couc loi ihc looIu incluucs ihc IP auuicss oi
hosinamc ol ihc icmoic scivicc lccausc ihai`s whcic
ihc RMI icgisiiy is iunning) nrJ ihc logical namc ihc
scivicc was icgisicicu unuci.
Bui wiih ]ini, ihc clicni has io Inow only onc ihing: Le
inter[oce .IeereJ b, Le e...e Thai`s ii.
So how uo you hnu ihings. Thc iiicI icvolvcs aiounu ]ini looIu
sciviccs. ]ini looIu sciviccs aic lai moic owcilul anu ucxillc ihan
ihc RMI icgisiiy. Ioi onc ihing, ]ini looIu sciviccs announcc ihcmsclvcs io ihc
nciwoiI, nuon.nII,. Whcn a looIu scivicc comcs onlinc, ii scnus a mcssagc using IP
muliicasi) oui io ihc nciwoiI saying, I`m hcic, il anyonc`s inicicsicu."
Bui ihai`s noi all. Ici`s say you a clicni) comc onlinc ne. ihc looIu scivicc has alicauy
announccu iiscll, ,ou can scnu a mcssagc io ihc cniiic nciwoiI saying, Aic ihcic any
looIu sciviccs oui ihcic."
Excci ihai you`ic noi ically inicicsicu in ihc looIu scivicc .eI-you`ic inicicsicu in
ihc sciviccs ihai aic .e.e.eJ wiih ihc looIu scivicc. Things liIc RMI icmoic sciviccs,
oihci sciializallc ]ava ol|ccis, anu cvcn ucviccs such as iinicis, camcias, anu collcc-
maIcis.
Anu hcic`s whcic ii gcis cvcn moic lun: whcn a scivicc comcs onlinc, ii will uynamically
uiscovci anu .e.e. iiscll wiih) any ]ini looIu sciviccs on ihc nciwoiI. Whcn ihc
scivicc icgisicis wiih ihc looIu scivicc, ihc scivicc scnus a sciializcu ol|cci io lc laccu
in ihc looIu scivicc. Thai sciializcu ol|cci can lc a siul io an RMI icmoic scivicc, a
uiivci loi a nciwoiIcu ucvicc, oi cvcn ihc wholc scivicc iiscll ihai oncc you gci ii liom
ihc looIu scivicc) iuns locally on youi machinc. Anu insicau ol icgisiciing ly rne, ihc
scivicc icgisicis ly ihc .re.ne ii imlcmcnis.
Oncc you ihc clicni) havc a iclcicncc io a looIu scivicc, you can say io ihai looIu
scivicc, Hcy, uo you havc anyihing ihai imlcmcnis ScicniihcCalculaioi." Ai ihai oini,
ihc looIu scivicc will chccI iis lisi ol icgisicicu inicilaccs, anu assuming ii hnus a
maich, says lacI io you, Ycs I Jo havc somcihing ihai imlcmcnis ihai inicilacc. Hcic`s
ihc sciializcu ol|cci ihc ScicniihcCalculaioi scivicc icgisicicu wiih mc."
a IittIe Jini
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 633
4zp!| vc 4|srevcry |n zr!|en
1
Jini Iookup service is Iounched somewhere on fhe nefwork, ond
onnounces ifseIf using IP muIficosf.
2
An oIreody-running Jini service on
onofher mochine osks fo be regisfered
wifh fhis newIy-onnounced Iookup
service. If regisfers by copobiIify,
rofher fhon by nome. In ofher words,
if regisfers os fhe service inferfoce if
impIemenfs. If sends o serioIi;ed objecf
fo be pIoced in fhe Iookup service.
Jini Lookup 8ervice
muchine on the network
somewhere,,,
Hey everybody,
I'm herel
unother muchine on the network
unother muchine on the network
Jini Lookup 8ervice
muchine on the network
somewhere,,,
unother muchine on the network
unother muchine on the network
Jini 8ervice
Pegisfer
me os somefhing
fhof impIemenfs
ScienfifcCoIcuIofor. Here's o
serioIi;ed objecf fhof represenfs
my service. Send if fo
onybody who osks...
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
634 chapter 18
4zp!| vc 4|srevcry |n zr!|en, ren!|nec4...
3
A cIienf on fhe nefwork wonfs
somefhing fhof impIemenfs fhe
ScienfifcCoIcuIofor inferfoce. If hos
no ideo where (or if) fhof fhing exisfs,
so if osks fhe Iookup service.
4
The Iookup service responds, since if does hove somefhing
regisfered os o ScienfifcCoIcuIofor inferfoce.
Jini Lookup 8ervice
muchine on the network
somewhere,,,
Do you
hove onyfhing
fhof impIemenfs
ScienfifcCoIcuIofor7
unother muchine on the network
unother muchine
on the network
Jini Lookup 8ervice
muchine on the network
somewhere,,,
unother muchine on the network
unother muchine on the network
Jini 8ervice
Jini 8ervice
Java app
Java app
Yes, I do
hove somefhing.
I'm sending you fhe
serioIi;ed objecf
now...
adaptive discovery in Jini
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 635
8c|f-hcz||n] nc! werk |n zr!|en
1
A Jini Service hos osked fo regisfer wifh fhe Iookup service. The Iookup
service responds wifh o "Ieose". The newIy-regisfered service musf keep
renewing fhe Ieose, or fhe Iookup service ossumes fhe service hos gone
ofine. The Iookup service wonfs oIwoys fo presenf on occurofe picfure
fo fhe resf of fhe nefwork obouf which services ore ovoiIobIe.
2
The service goes offIine (somebody shufs if down), so if foiIs fo
renew ifs Ieose wifh fhe Iookup service. The Iookup service drops if.
Jini Lookup 8ervice
muchine on the network
somewhere,,,
I'II
regisfer you,
ond here's your
Ieose. If you don'f
renew if, I'II drop you.
unother muchine on the network
unother muchine
on the network
Jini Lookup 8ervice
muchine on the network
somewhere,,,
unother muchine on the network
unother muchine on the network
Jini 8ervice
Hmmmm... I
didn'f gef o Ieose
renewoI from fhof one... if
musf be down. I'II drop if. If if
comes bock, if wiII oufomoficoIIy
rediscover me.
Ieuse
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
636 chapter 18
I|nz| |rejcr!: !hc 0n| vcrsz| 8crv|rc |rewscr
Wc`ic going io maIc somcihing ihai isn`i ]ini-cnallcu, lui quiic casily coulu lc.
Ii will givc you ihc uavoi anu lccling ol ]ini, lui using siiaighi RMI. In laci ihc
main uillcicncc lciwccn oui alicaiion anu a ]ini alicaiion is how ihc scivicc is
uiscovcicu. Insicau ol ihc ]ini looIu scivicc, which auiomaiically announccs iiscll anu
livcs anywhcic on ihc nciwoiI, wc`ic using ihc RMI icgisiiy which musi lc on ihc samc
machinc as ihc icmoic scivicc, anu which uocs noi announcc iiscll auiomaiically.
Anu insicau ol oui scivicc icgisiciing iiscll auiomaiically wiih ihc looIu scivicc, we
havc io icgisici ii in ihc RMI icgisiiy using Naming.iclinu)).
Bui oncc ihc clicni has lounu ihc scivicc in ihc RMI icgisiiy, ihc icsi ol ihc alicaiion
is almosi iucniical io ihc way wc`u uo ii in ]ini. Thc main ihing missing is ihc Iene ihai
woulu lci us havc a scll-hcaling nciwoiI il any ol ihc sciviccs go uown.)
Thc univcisal scivicc liowsci is liIc a sccializcu wcl liowsci, cxcci insicau ol HTMI
agcs, ihc scivicc liowsci uownloaus anu uislays iniciaciivc ]ava GUIs ihai wc`ic
calling ur..e.nI e...e.
w
-- ]-- :-|-:l . :--:-,
l -|| :-- - --- '
c--:- . :--:- --- l-
|:l 1- M| ----l- :--:-
.: . -l--:-|:l|`
--l- l.l :--: .: l:
|:l - :--:-:
w-- l- -:-- :-|-:l: ---,
l- :|--l .:: -- l-
.:l-.| :--:- |l:--||-,
l.]61-w--, -l:` l-
- :--l .: --- l- M|
----l- :--:-
universaI service project
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 637
How it works:
1 CIienf sforfs up ond
does o Iookup on fhe
PMI regisfry for
fhe service coIIed
"ServiceServer", ond
gefs bock fhe sfub.
Server
Service rowser
{cIient}
"
P
Ie
o
s
e
g
iv
e
m
e
f
h
e
f
h
in
g
n
o
m
e
d
"
S
e
r
v
ic
e
S
e
r
v
e
r
"
Server
Service rowser
{cIient}
"gefServiceLisf()"
"OI, here's on orroy of services"
Ser
v
ic
e
S
e
r
v
e
r
Stub
PMI registry {on server}
"
O
I
,
h
e
r
e
's
f
h
e
s
f
u
b
"
2 CIienf coIIs gefServiceLisf() on fhe sfub. The ServiceServer
refurns on orroy of services
Server
Service rowser
{cIient}
Ser
v
ic
e
S
e
r
v
e
r
3 CIienf dispIoys fhe Iisf of services in o 0UI
Ser
v
ic
e
S
e
r
v
e
r
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
638 chapter 18
Server
Service rowser
{cIient}
Ser
v
ic
e
S
e
r
v
e
r
4 User seIecfs from fhe Iisf, so cIienf coIIs fhe gefService()
mefhod on fhe remofe service. The remofe service refurns o
serioIi;ed objecf fhof is on ocfuoI service fhof wiII run inside
fhe cIienf browser.
How it works, continued...
universaI service browser
"gefService(seIecfedSvc)"
"OI, here's fhe service"
Service rowser
{cIient}
5 CIienf coIIs fhe gef0uiPoneI() on fhe serioIi;ed service objecf if
jusf gof from fhe remofe service. The 0UI for fhof service is
dispIoyed inside fhe browser, ond fhe user con inferocf wifh if
IocoIIy. Af fhis poinf, we don'f need fhe remofe service unIess/unfiI
fhe user decides fo seIecf onofher service.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 639
1 interfuce ServiceServer impIements Pemote
A reguIor oId PMI remofe inferfoce for fhe remofe service (fhe
remofe service hos fhe mefhod for geffing fhe service Iisf ond
refurning o seIecfed service).
The classes and interfaces:
2 cIuss ServiceServerImpI impIements ServiceServer
The ocfuoI PMI remofe service (exfends UnicosfPemofeObjecf).
Ifs job is fo insfonfiofe ond sfore oII fhe services (fhe fhings
fhof wiII be shipped fo fhe cIienf), ond regisfer fhe server ifseIf
(ServiceServerImpI) wifh fhe PMI regisfry.
3 cIuss Servicerowser
The cIienf. If buiIds o very simpIe 0UI, does o Iookup in fhe PMI
regisfry fo gef fhe ServiceServer sfub, fhen coIIs o remofe mefhod on
if fo gef fhe Iisf of services fo dispIoy in fhe 0UI Iisf.
4 interfuce Service
This is fhe key fo everyfhing. This very simpIe inferfoce hos jusf one
mefhod, gef0uiPoneI(). Every service fhof gefs shipped over fo fhe
cIienf musf impIemenf fhis inferfoce. This is whof mokes fhe whoIe fhing
UMIVEPSALl 8y impIemenfing fhis inferfoce, o service con come over
even fhough fhe cIienf hos no ideo whof fhe ocfuoI cIoss (or cIosses)
ore fhof moke up fhof service. AII fhe cIienf knows is fhof whofever
comes over, if impIemenfs fhe Service inferfoce, so if MUST hove o
gef0uiPoneI() mefhod.
The cIienf gefs o serioIi;ed objecf os o resuIf of coIIing
gefService(seIecfedSvc) on fhe ServiceServer sfub, ond oII fhe cIienf
soys fo fhof objecf is, "I don'f know who or whof you ore, buf I DO
know fhof you impIemenf fhe Service inferfoce, so I know I con coII
gef0uiPoneI() on you. And since gef0uiPoneI() refurns o JPoneI, I'II jusf
sIop if info fhe browser 0UI ond sforf inferocfing wifh ifl
5 cIuss DiceService impIements Service
0of dice7 If nof, buf you need some, use fhis service fo roII onywhere
from I fo o virfuoI dice for you.
6 cIuss MiniMusicService impIements Service
Pemember fhof fobuIous IiffIe 'music video' progrom from fhe frsf
0UI Code Iifchen7 We've furned if info o service, ond you con pIoy if
over ond over ond over unfiI your roommofes fnoIIy Ieove.
7 cIuss DuyOfTheWeekService impIements Service
Were you born on o Fridoy7 Type in your birfhdoy ond fnd ouf.
ger$erv|oesL|sr{j
ger$erv|oe{j
8erv|ce8erver|mp|
el3erv|cesL|sl()
el3erv|ce()
8erv|cerowser
ra|r()
gerSu|Pane|{j
0|ce8erv|ce
el0u|Pare|()
H|n|Hus|c8erv|ce
el0u|Pare|()
0ay0fTheweek8erv|ce
el0u|Pare|()
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
640 chapter 18
universaI service code
interface 8ervice8erver {the remote interface}
import java.rmi.*;
public interface ServiceServer extends Remote {
Object[] getServiceList() throws RemoteException;
Service getService(Object serviceKey) throws RemoteException;
}
interface 8ervice {what the GU services implement}
import javax.swing.*;
import java.io.*;
public interface Service extends Serializable {
public JPanel getGuiPanel();
}
A ----.| M
| ----l- -l--.:-,
---: l- l-- --l-: l-
----l- :--:- -|| .-
A |.- -| |- ---~----l-` -l--.:-, l.l
---: l- --- --l- l.l .-] ----:.|
:--:- --:l .---l6-|.--||` 1-
-l--.:- -l--: --.|-.|-, :- l.l .-]
:|.:: -|----l- l- --:- -l--.:- -||
.-l--.l:.||] - --.|-.|-
1.l': . --:l, -:.-:- l- :--:-: -l
:- --- l- --- --- l- :----, .: .
--:-|l - l- :|--l :.||- -l--:-|` --
l- ----l- --:-----
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 641
import java.rmi.*;
import java.util.*;
import java.rmi.server.*;
public class ServiceServerImpl extends UnicastRemoteObject implements ServiceServer {
HashMap serviceList;
public ServiceServerImpl() throws RemoteException {
setUpServices();
}
private void setUpServices() {
serviceList = new HashMap();
serviceList.put(Dice Rolling Service, new DiceService());
serviceList.put(Day of the Week Service, new DayOfTheWeekService());
serviceList.put(Visual Music Service, new MiniMusicService());
}
public Object[] getServiceList() {
System.out.println(in remote);
return serviceList.keySet().toArray();
}
public Service getService(Object serviceKey) throws RemoteException {
Service theService = (Service) serviceList.get(serviceKey);
return theService;
}
public static void main (String[] args) {
try {
Naming.rebind(ServiceServer, new ServiceServerImpl());
} catch(Exception ex) {
ex.printStackTrace();
}
System.out.println(Remote service is running);
}
}
class 8ervice8ervermpl {the remote implementation}
A ----.| M
| -|----l.l--
1- :--:-: -|| - :l--- - . +.:M. :-||-:l-- |-:l-. - -ll- 6N!
--:l - l- :-||-:l--, ]-- -l 1w6 ~~ . -] --:l ||- . l--` .- .
.|-- --:l |-.l--- ]-- -.-l` |:-- .-- B -- ---- -- +.:M.`
w-- l- :--:l--:l-- : :.||-, -l.|-- l- .:l-.|
----:.| :--:-: |l:---:-, M-M-::--:-, -l:`
c|--l :.||: l: - ---- l- -l . |:l - :--:-: l-
:|.] - l- ---:-- |:- l- -:-- :.- :-|-:l ---` w-
:-- .- .--.] - l]- 6-:l |--- l-- l .: l--:
-:-` ] -.- .- .--.] - -:l l- r!/ l.l .--
- l- +.:M. w- ---'l :-- .- .:l-.| --:- --:l
--|-:: l- :|--l .:: -- l ] :.||- -l--:-|`
M.- l- :--:-: |l- .:l-.| :--:-
--:l:` .- -l l-- -l- l-
+.:M., -l . l-- -.-- |--
l- '-]'`
c|--l :.||: l: --l- .l-- l- -:-- :-|-:l: . :--:-
--- l- :|.]- |:l - :--:-: |l.l l -l --- l-
--l- .--` 1: :-- -:-: l- -] |l- :.-- -]
---.||] :--l l- l- :|--l` l- -l l- :----:---
:--:- --l - l- +.:M.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
642 chapter 18
import java.awt.*;
import javax.swing.*;
import java.rmi.*;
import java.awt.event.*;
public class ServiceBrowser {
JPanel mainPanel;
JComboBox serviceList;
ServiceServer server;
public void buildGUI() {
JFrame frame = new JFrame(RMI Browser);
mainPanel = new JPanel();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
Object[] services = getServicesList();
serviceList = new JComboBox(services);
frame.getContentPane().add(BorderLayout.NORTH, serviceList);
serviceList.addActionListener(new MyListListener());
frame.setSize(500,500);
frame.setVisible(true);
}
void loadService(Object serviceSelection) {
try {
Service svc = server.getService(serviceSelection);
mainPanel.removeAll();
mainPanel.add(svc.getGuiPanel());
mainPanel.validate();
mainPanel.repaint();
} catch(Exception ex) {
ex.printStackTrace();
}
}
class 8erviceBrowser {the client}
l: --l- --: l- M| --:l-] |---,
-l: l- :l-, .- :.||: -l--:-|:l|`
|1- .:l-.| --l- : -- l- --l .-`
A l- :--:-: |.- .--.] - 6-:l:` l- l-
)c---B- |l- |:l` 1- )c---B- ---: -- l-
-.- :|.].|- l--: --l - -.: l- - l- .--.]
+---': ---- -- . l- .:l-.| :--:- l- l- 6c|, .l-- l-
-:-- .: :-|-:l- --- |1: --l- : :.||- ] l- ---l
|:l---- -- l- )c---B-` w- :.|| -l--:-|` -- l-
----l- :---- |l- :l- -- --:-----` .- .:: l l-
l-- l.l -.: :|.]- - l- |:l |-: : l- AM!
l-- -- ---.||] -l --- l- :---- --- -- :.||-
-l--:-|:l|`` 1- :---- --l---: l- .:l-.| :--:-
|:--.|--`, -: : .-l--.l:.||] -:--.|-- |l.-: l- M|`
.- -- :-|] :.|| l- -l6-|.--||` -- l- :--:- .- .
l- --:-|l |. )|.--|` l- l- ---:--': -.-|.--|
ServiceBrowser code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 643
Object[] getServicesList() {
Object obj = null;
Object[] services = null;
try {
obj = Naming.lookup(rmi://127.0.0.1/ServiceServer);
}
catch(Exception ex) {
ex.printStackTrace();
}
server = (ServiceServer) obj;
try {
services = server.getServiceList();
} catch(Exception ex) {
ex.printStackTrace();
}
return services;
}
class MyListListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
Object selection = serviceList.getSelectedItem();
loadService(selection);
}
}
public static void main(String[] args) {
new ServiceBrowser().buildGUI();
}
}
l- l- M| |---, .- -l l- :l-
c.:l l- :l- l- l- ----l- -l--.:- l]-,
:- l.l -- :.- :.|| -l--:-|:l|` -- l
-l--:-|:l|` -: -: l- .--.] - 6-:l:,
l.l -- :|.] - l- )c---B- -- l- -:-- l-
:-|-:l ---
| --'-- ---, l --.-: l- -:-- -.- .
:-|-:l-- --- l- )c---B- |:l -,
l.- l- :-|-:l-- l-] -.- .- |-. l-
.---.l- :--:- |:-- l- |-.--:- --l-
-- l- ----: .-, l.l .:: l- :---- --
l- :--:- l.l :----:--: -l l: :-|-:l--`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
644 chapter 18
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class DiceService implements Service {
JLabel label;
JComboBox numOfDice;
public JPanel getGuiPanel() {
JPanel panel = new JPanel();
JButton button = new JButton(Roll `em!);
String[] choices = {1, 2, 3, 4, 5};
numOfDice = new JComboBox(choices);
label = new JLabel(dice values here);
button.addActionListener(new RollEmListener());
panel.add(numOfDice);
panel.add(button);
panel.add(label);
return panel;
}
public class RollEmListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
// roll the dice
String diceOutput = ;
String selection = (String) numOfDice.getSelectedItem();
int numOfDiceToRoll = Integer.parseInt(selection);
for (int i = 0; i < numOfDiceToRoll; i++) {
int r = (int) ((Math.random() * 6) + 1);
diceOutput += ( + r);
}
label.setText(diceOutput);
}
}
class Dice8ervice {a universal service, implements 8ervice}
+---': l- --- ---l.-l --l-' 1- --l- - l-
--:- -l--.:-~~ l- --- l- :|--l': ---. :.|| ---
l: :--:- : :-|-:l- .- |-.- /-- :.- - -.l--- ]--
-.-l - l- -l6-|.--||` --l-, .: |-- .: ]-- --l--- .
)|.--|, :- l -|: l- .:l-.| :-~--||- 6c|
+,-+ :+ ,-+:.|
Think about ways to improve the DiceService. One
suggestion: using what you learned in the GU| chapters,
make the dice graphical. Use a rectangle, and draw the
appropriate number of circles on each one, corresponding
to the roll for that particular die.
DiceService code
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 645
class MiniMusic8ervice {a universal service, implements 8ervice}
import javax.sound.midi.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MiniMusicService implements Service {
MyDrawPanel myPanel;
public JPanel getGuiPanel() {
JPanel mainPanel = new JPanel();
myPanel = new MyDrawPanel();
JButton playItButton = new JButton(Play it);
playItButton.addActionListener(new PlayItListener());
mainPanel.add(myPanel);
mainPanel.add(playItButton);
return mainPanel;
}
public class PlayItListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
try {
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
sequencer.addControllerEventListener(myPanel, new int[] {127});
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
for (int i = 0; i < 100; i+= 4) {
int rNum = (int) ((Math.random() * 50) + 1);
if (rNum < 38) { // so now only do it if num <38 (75% of the time)
track.add(makeEvent(144,1,rNum,100,i));
track.add(makeEvent(176,1,127,0,i));
track.add(makeEvent(128,1,rNum,100,i + 2));
}
} // end loop
sequencer.setSequence(seq);
sequencer.start();
sequencer.setTempoInBPM(220);
} catch (Exception ex) {ex.printStackTrace();}
} // close actionperformed
} // close inner class
1: : .|| l- --:: :l- --- l-
c-- rl:-- - :.l-- |i, :- --
---'l .---l.l- l ..- ---
1- :--:- --l-' A|| l
--: : :|.] . -ll-- .-
l- -.-- :--:- |----
l- --:l.-|-: -|| ---l-.||]
- .-l-`
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
646 chapter 18
public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) {
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);
}catch(Exception e) { }
return event;
}
class MyDrawPanel extends JPanel implements ControllerEventListener {
// only if we got an event do we want to paint
boolean msg = false;
public void controlChange(ShortMessage event) {
msg = true;
repaint();
}
public Dimension getPreferredSize() {
return new Dimension(300,300);
}
public void paintComponent(Graphics g) {
if (msg) {
Graphics2D g2 = (Graphics2D) g;
int r = (int) (Math.random() * 250);
int gr = (int) (Math.random() * 250);
int b = (int) (Math.random() * 250);
g.setColor(new Color(r,gr,b));
int ht = (int) ((Math.random() * 120) + 10);
int width = (int) ((Math.random() * 120) + 10);
int x = (int) ((Math.random() * 40) + 10);
int y = (int) ((Math.random() * 40) + 10);
g.llRect(x,y,ht, width);
msg = false;
} // close if
} // close method
} // close inner class
} // close class
class MiniMusic8ervice, continued...
MiniMusicService code
N-l- --- -- l: --l-- .- /--'-
:--- l .|| - l- -.:: c--rl:--
| ]-- -.-l .--l-- ---::-, l-]
.---l.l- l: :-- ]---:-|, l--
:--.-- l -l l- c--rl:-- -
l- A --] -.: :l--]' :.l--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
remote depIoyment with RMI
you are here 647
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.text.*;
public class DayOfTheWeekService implements Service {
JLabel outputLabel;
JComboBox month;
JTextField day;
JTextField year;
public JPanel getGuiPanel() {
JPanel panel = new JPanel();
JButton button = new JButton(Do it!);
button.addActionListener(new DoItListener());
outputLabel = new JLabel(date appears here);
DateFormatSymbols dateStuff = new DateFormatSymbols();
month = new JComboBox(dateStuff.getMonths());
day = new JTextField(8);
year = new JTextField(8);
JPanel inputPanel = new JPanel(new GridLayout(3,2));
inputPanel.add(new JLabel(Month));
inputPanel.add(month);
inputPanel.add(new JLabel(Day));
inputPanel.add(day);
inputPanel.add(new JLabel(Year));
inputPanel.add(year);
panel.add(inputPanel);
panel.add(button);
panel.add(outputLabel);
return panel;
}
public class DoItListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
int monthNum = month.getSelectedIndex();
int dayNum = Integer.parseInt(day.getText());
int yearNum = Integer.parseInt(year.getText());
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, monthNum);
c.set(Calendar.DAY_OF_MONTH, dayNum);
c.set(Calendar.YEAR, yearNum);
Date date = c.getTime();
String dayOfWeek = (new SimpleDateFormat(EEEE)).format(date);
outputLabel.setText(dayOfWeek);
}
}
}
class DayOfTheWeek8ervice {a universal service, implements 8ervice}
1- --:- -l--.:- --l-
l.l -|: l- 6c|
--- l- :.l-- |o ]-- --- . ------
- -- ----- .- .l- ---.ll- ---:
1: :-- : :|l|] ----l, -----,
-:.-:- l -:-: l- c.|--.- :|.:: A|:-, l-
-|-l.l-|---.l |-l: -: :-:] . .ll---
-- -- l- .l- :--| --l --l
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
648 chapter 18
Caag:ata|atiaas!
)aa aJe it ta the eaJ.
WouIdn'f if be
dreomy if fhis were fhe end
of fhe book7 If fhere were no
more buIIef poinfs or pu;;Ies
or code Iisfings or onyfhing eIse7
8uf fhof's probobIy jusf o
fonfosy...
Of course, there's still the two appendices.
And the index.
And then there's the web site...
There's no escape, really.
the end... sort of
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
649
AeaJix A
Iiaa| CaJe kit:hea
Iiaa||y, the :a|ete ve:siaa aI the 5eat5ax!
!t :aaae:ts ta a si|e Kasi:Se:ve: sa that yaa :aa
seaJ aaJ :e:eive leat atte:as vith athe: :|ieats.
/--- --::.- -l: :--l l-
l- -l-- |.]--:, .|--
-l ]--- :-----l -.l
.ll---, --- ]-- l
:--|l'
Andy: groove #2
6hr|s: groove2 rev|sed
N|ge|: dance beat
dance beat
|-:--- --::.-: --- |.]--: c|: --- l- |-.
l- .ll--- l.l --: -l l, .- l-- :|: 'l.-l' l- |.] l
this is a new appendix
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
finaI BeatBox code
650 appendix A
import java.awt.*;
import javax.swing.*;
import java.io.*;
import javax.sound.midi.*;
import java.util.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.event.*;
public class BeatBoxFinal {
JFrame theFrame;
JPanel mainPanel;
JList incomingList;
JTextField userMessage;
ArrayList<JCheckBox> checkboxList;
int nextNum;
Vector<String> listVector = new Vector<String>();
String userName;
ObjectOutputStream out;
ObjectInputStream in;
HashMap<String, boolean[]> otherSeqsMap = new HashMap<String, boolean[]>();
Sequencer sequencer;
Sequence sequence;
Sequence mySequence = null;
Track track;
String[] instrumentNames = {Bass Drum, Closed Hi-Hat, Open Hi-Hat,Acoustic
Snare, Crash Cymbal, Hand Clap, High Tom, Hi Bongo, Maracas, Whistle,
Low Conga, Cowbell, Vibraslap, Low-mid Tom, High Agogo, Open Hi Conga};
int[] instruments = {35,42,46,38,49,39,50,60,70,72,64,56,58,47,67,63};
Final BeatBox client program
Most of this code is the same as the code from the CodeKitchens in the previous
chapters, so we don't annotate the whole thing again. The new parts include:
GU - two new components are added for the text area that displays incoming
messages (actually a scrolling list) and the text feld.
NETWORKNG - just like the SimpleChatClient in this chapter, the BeatBox now
connects to the server and gets an input and output stream.
THREADS - again, just like the SimpleChatClient, we start a 'reader' class that
keeps looking for incoming messages from the server. But instead of just text, the
messages coming in include TWO objects: the String message and the serialized
ArrayList (the thing that holds the state of all the checkboxes.)
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
appendix A FinaI Code Kitchen
you are here 651
public static void main (String[] args) {
new BeatBoxFinal().startUp(args[0]); // args[0] is your user ID/screen name
}
public void startUp(String name) {
userName = name;
// open connection to the server
try {
Socket sock = new Socket(127.0.0.1, 4242);
out = new ObjectOutputStream(sock.getOutputStream());
in = new ObjectInputStream(sock.getInputStream());
Thread remote = new Thread(new RemoteReader());
remote.start();
} catch(Exception ex) {
System.out.println(couldn't connect - you'll have to play alone.);
}
setUpMidi();
buildGUI();
} // close startUp
public void buildGUI() {
theFrame = new JFrame(Cyber BeatBox);
BorderLayout layout = new BorderLayout();
JPanel background = new JPanel(layout);
background.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
checkboxList = new ArrayList<JCheckBox>();
Box buttonBox = new Box(BoxLayout.Y_AXIS);
JButton start = new JButton(Start);
start.addActionListener(new MyStartListener());
buttonBox.add(start);
JButton stop = new JButton(Stop);
stop.addActionListener(new MyStopListener());
buttonBox.add(stop);
JButton upTempo = new JButton(Tempo Up);
upTempo.addActionListener(new MyUpTempoListener());
buttonBox.add(upTempo);
JButton downTempo = new JButton(Tempo Down);
downTempo.addActionListener(new MyDownTempoListener());
buttonBox.add(downTempo);
JButton sendIt = new JButton(sendIt);
sendIt.addActionListener(new MySendListener());
buttonBox.add(sendIt);
userMessage = new JTextField();
A . :---.-~|-- .-----l -- ]--- ::---- -.--
!.-|- * .. B-.lB-|-.| l-||.:
N-l- --- :-l - l-
--l----, |/6, .- -.- |.-
:l.-l` l- --.-- l--.
6c| :--, --l- --- ---
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
finaI BeatBox code
652 appendix A
buttonBox.add(userMessage);
incomingList = new JList();
incomingList.addListSelectionListener(new MyListSelectionListener());
incomingList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane theList = new JScrollPane(incomingList);
buttonBox.add(theList);
incomingList.setListData(listVector); // no data to start with
Box nameBox = new Box(BoxLayout.Y_AXIS);
for (int i = 0; i < 16; i++) {
nameBox.add(new Label(instrumentNames[i]));
}
background.add(BorderLayout.EAST, buttonBox);
background.add(BorderLayout.WEST, nameBox);
theFrame.getContentPane().add(background);
GridLayout grid = new GridLayout(16,16);
grid.setVgap(1);
grid.setHgap(2);
mainPanel = new JPanel(grid);
background.add(BorderLayout.CENTER, mainPanel);
for (int i = 0; i < 256; i++) {
JCheckBox c = new JCheckBox();
c.setSelected(false);
checkboxList.add(c);
mainPanel.add(c);
} // end loop
theFrame.setBounds(50,50,300,300);
theFrame.pack();
theFrame.setVisible(true);
} // close buildGUI
public void setUpMidi() {
try {
sequencer = MidiSystem.getSequencer();
sequencer.open();
sequence = new Sequence(Sequence.PPQ,4);
track = sequence.createTrack();
sequencer.setTempoInBPM(120);
} catch(Exception e) {e.printStackTrace();}
} // close setUpMidi
)|:l : . :------l -- .--'l
-:- ---- 1: : ---- l-
-:--- --::.-: .-- :|.]-
6-|] -:l-. - . ----.| :.l
---- ]-- -:l |66r .l l-
--::.-:, - l: . ]-- :.-
!|!c1 . --::.- --- l- |:l
l- |-. .- |.] l- .ll.:-
-.l .ll---
N-l- -|:- -- l: .- : ---
6-l l- ----:--, -.- .
----:-, .- -.- . 1-.:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
appendix A FinaI Code Kitchen
you are here 653
public void buildTrackAndStart() {
ArrayList<Integer> trackList = null; // this will hold the instruments for each
sequence.deleteTrack(track);
track = sequence.createTrack();
for (int i = 0; i < 16; i++) {
trackList = new ArrayList<Integer>();
for (int j = 0; j < 16; j++) {
JCheckBox jc = (JCheckBox) checkboxList.get(j + (16*i));
if (jc.isSelected()) {
int key = instruments[i];
trackList.add(new Integer(key));
} else {
trackList.add(null); // because this slot should be empty in the track
}
} // close inner loop
makeTracks(trackList);
} // close outer loop
track.add(makeEvent(192,9,1,0,15)); // - so we always go to full 16 beats
try {
sequencer.setSequence(sequence);
sequencer.setLoopCount(sequencer.LOOP_CONTINUOUSLY);
sequencer.start();
sequencer.setTempoInBPM(120);
} catch(Exception e) {e.printStackTrace();}
} // close method
public class MyStartListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
buildTrackAndStart();
} // close actionPerformed
} // close inner class
public class MyStopListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
sequencer.stop();
} // close actionPerformed
} // close inner class
public class MyUpTempoListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
oat tempoFactor = sequencer.getTempoFactor();
sequencer.setTempoFactor((oat)(tempoFactor * 1.03));
} // close actionPerformed
} // close inner class
B-| . l-.: ] -.|- l--- l- :-:--:
l- -l l-- :l.l-, .- -.- l.l l- .-
-:l-----l |.- -.- l- M!--l -- l`
1: : --ll] :--|-, -l l : !xAc1|/ .: l
-.: - l- ----: :.l--:, :- ---- l- ----:
c--rl:--: l- -l l- -|| -|.-.l-- ..-
1- 6c| |:l----:
!.:l|] l- :.-- .: l-
----: :.l--': --:--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Eduard Simons
104038
finaI BeatBox code
654 appendix A
public class MyDownTempoListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
oat tempoFactor = sequencer.getTempoFactor();
sequencer.setTempoFactor((oat)(tempoFactor * .97));
}
}
public class MySendListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
// make an arraylist of just the STATE of the checkboxes
boolean[] checkboxState = new boolean[256];
for (int i = 0; i < 256; i++) {
JCheckBox check = (JCheckBox) checkboxList.get(i);
if (check.isSelected()) {
checkboxState[i] = true;
}
} // close loop
String messageToSend = null;
try {
out.writeObject(userName + nextNum++ + : + userMessage.getText());
out.writeObject(checkboxState);
} catch(Exception ex) {
System.out.println(Sorry dude. Could not send it to the server.);
}
userMessage.setText();
} // close actionPerformed
} // close inner class
public class MyListSelectionListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent le) {
if (!le.getValueIsAdjusting()) {
String selected = (String) incomingList.getSelectedValue();
if (selected != null) {
// now go to the map, and change the sequence
boolean[] selectedState = (boolean[]) otherSeqsMap.get(selected);
changeSequence(selectedState);
sequencer.stop();
buildTrackAndStart();
}
}
} // close valueChanged
} // close inner class
1: : --- l': . |-l |- l- -|-c.lc|--l, -:-l
-:l-. - :--- . l-- --::.-, -- :--.|-- l-- --:l:
|l- l-- --::.- .- l- -.l .ll---` .- --l- l-:-
l-- --:l: l- l- :-:-l --l-l :l--.- |l- l- :----`
1: : .|:- --- ~~ . |:l-|-:l--|:l---- l.l l-||: -:
--- l- -:-- -.- . :-|-:l-- -- l- |:l - --::.-:
w-- l- -:-- :-|-:l: . --::.-, -- |M
M
!l|A1!|/
|-. l- .::-:.l- -.l .ll--- |l': - l- +.:M
.
:.||- -l---:M
.` .- :l.-l |.]- l 1---': :---
l-:l: -:.-:- - |ll|- --] l-: .--l -ll-
|:l-|-:l--!--l:
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
appendix A FinaI Code Kitchen
you are here 655
public class RemoteReader implements Runnable {
boolean[] checkboxState = null;
String nameToShow = null;
Object obj = null;
public void run() {
try {
while((obj=in.readObject()) != null) {
System.out.println(got an object from server);
System.out.println(obj.getClass());
String nameToShow = (String) obj;
checkboxState = (boolean[]) in.readObject();
otherSeqsMap.put(nameToShow, checkboxState);
listVector.add(nameToShow);
incomingList.setListData(listVector);
} // close while
} catch(Exception ex) {ex.printStackTrace();}
} // close run
} // close inner class
public class MyPlayMineListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
if (mySequence != null) {
sequence = mySequence; // restore to my original
}
} // close actionPerformed
} // close inner class
public void changeSequence(boolean[] checkboxState) {
for (int i = 0; i < 256; i++) {
JCheckBox check = (JCheckBox) checkboxList.get(i);
if (checkboxState[i]) {
check.setSelected(true);
} else {
check.setSelected(false);
}
} // close loop
} // close changeSequence
public void makeTracks(ArrayList list) {
Iterator it = list.iterator();
for (int i = 0; i < 16; i++) {
Integer num = (Integer) it.next();
if (num != null) {
int numKey = num.intValue();
track.add(makeEvent(144,9,numKey, 100, i));
track.add(makeEvent(128,9,numKey,100, i + 1));
}
} // close loop
} // close makeTracks()
1: : l- l--. - ~~ --. - .l.
--- l- :---- |- l: :--, '.l.' -||
.|-.]: - l-- :--.|-- --:l: l-
l-- --::.- .- l- -.l .ll--- |.-
A--.]|:l - :-:- :l.l- .|--:`
w
-- . --::.- :---: -, -- --.
|-:--.|--` l- l-- --:l: |l-
--::.- .- l- A
--.]|
:l - B
--|-.-
:-:- :l.l- .|--:` .- . l l-
l- )|
:l :------l A
- l- . )|
:l
: . l--~:l- l- ]-- -- . /
-:l--
- l- |:l: .l. |/
-:l-- : .- -|~
.:--- A
--.]|
:l`, .- l-- l-|| l-
)|
:l l- -:- l.l /
-:l-- .: l': :---:-
-- -.l l- :|.] - l- |:l
1: --l- : :.||- --- l- -:-- :-|-:l:
:---l- --- l- |:l w- |MM!l|A1!|/
:.-- l- .ll--- l- l- --- l-] :-|-:l-
A|| l- M|l| :l- : -.:l|] l- :.-- .: l
-.: - l- ----: --:--
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
finaI BeatBox code
656 appendix A
public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) {
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);
}catch(Exception e) { }
return event;
} // close makeEvent
} // close class
N-l- --- )-:l |- l- |.:l --:--
+,-+ :+ ,-+:.|
what are some of the ways you can improve this programI
Here are a few ideas to get you started:
l) Once you select a pattern, whatever current pattern was playing is blown
away. |f that was a new pattern you were working on (or a modification of
another one), you're out of luck. ou might want to pop up a dialog box that
asks the user if he'd like to save the current pattern.
2) |f you fail to type in a command-line argument, you |ust get an exception
when you run it! Put something in the main method that checks to see if
you've passed in a command-line argument. |f the user doesn't supply one,
either pick a default or print out a message that says they need to run it
again, but this time with an argument for their screen name.
3) |t might be nice to have a feature where you can click a button and it
will generate a random pattern for you. ou might hit on one you really like.
8etter yet, have another feature that lets you load in existing 'foundation'
patterns, like one for |azz, rock, reggae, etc. that the user can add to.
ou can find existing patterns on the Head Pirst 1ava web start.
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
appendix A FinaI Code Kitchen
you are here 657
import java.io.*;
import java.net.*;
import java.util.*;
public class MusicServer {
ArrayList<ObjectOutputStream> clientOutputStreams;
public static void main (String[] args) {
new MusicServer().go();
}
public class ClientHandler implements Runnable {
ObjectInputStream in;
Socket clientSocket;
public ClientHandler(Socket socket) {
try {
clientSocket = socket;
in = new ObjectInputStream(clientSocket.getInputStream());
} catch(Exception ex) {ex.printStackTrace();}
} // close constructor
public void run() {
Object o2 = null;
Object o1 = null;
try {
while ((o1 = in.readObject()) != null) {
o2 = in.readObject();
System.out.println(read two objects);
tellEveryone(o1, o2);
} // close while
} catch(Exception ex) {ex.printStackTrace();}
} // close run
} // close inner class
Final BeatBox server program
Most of this code is identical to the SimpleChatServer we made in the
Networking and Threads chapter. The only difference, in fact, is that this server
receives, and then re-sends, two serialized objects instead of a plain String
(although one of the serialized objects happens to a String).
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
finaI BeatBox code
658 appendix A
public void go() {
clientOutputStreams = new ArrayList<ObjectOutputStream>();
try {
ServerSocket serverSock = new ServerSocket(4242);
while(true) {
Socket clientSocket = serverSock.accept();
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
clientOutputStreams.add(out);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println(got a connection);
}
}catch(Exception ex) {
ex.printStackTrace();
}
} // close go
public void tellEveryone(Object one, Object two) {
Iterator it = clientOutputStreams.iterator();
while(it.hasNext()) {
try {
ObjectOutputStream out = (ObjectOutputStream) it.next();
out.writeObject(one);
out.writeObject(two);
}catch(Exception ex) {ex.printStackTrace();}
}
} // close tellEveryone
} // close class
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
we covered a lot of ground, and you're almost finished with this book. we'll miss you, but before
we let you go, we wouldn't feel right about sending you out into 1avaLand without a little more
preparation. we can't possibly fit everything you'll need to know into this relatively small appendix.
Actually, we originally include everything you need to know about 1ava (not already covered by
the other chapters), by reducing the type point size to .00003. |t all fit, but nobody could read it. So,
we threw most of it away, but kept the best bits for this Top Ten appendix.
This really the end of the book. Lxcept for the index (a must-read!).
Appendix B
The Top Ten Topics that almost made it into the Real Book...
You meon, fhere's sfiII
MOPE7 Doesn'f fhis
book EVEP end7
659 this is a new appendix
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
660 appendix B
#10 Bit Manipulation
Why 4e yee rzrc!
Wc`vc ialIcu aloui ihc laci ihai ihcic aic S liis in a lyic,
16 liis in a shoii, anu so on. You mighi havc occasion io
iuin inuiviuual liis on oi oll. Ioi insiancc you mighi hnu
youiscll wiiiing couc loi youi ncw ]ava cnallcu ioasici,
anu icalizc ihai uuc io scvcic mcmoiy limiiaiions, cciiain
ioasici sciiings aic coniiollcu ai ihc lii lcvcl. Ioi casici
icauing, wc`ic showing only ihc lasi S liis in ihc commcnis
iaihci ihan ihc lull S2 loi an ini).
Bitwise NOT Operator: ~
This ociaioi uis all ihc liis` ol a iimiiivc.
int x = 10; // bits are 0000I0I0
x = ~x; // bits are now IIII0I0I
Thc ncxi ihicc ociaiois comaic iwo iimiiivcs on a lii
ly lii lasis, anu iciuin a icsuli lascu on comaiing ihcsc
liis. Wc`ll usc ihc lollowing cxamlc loi ihc ncxi ihicc
ociaiois:
int x = 10; // bits are 0000I0I0
int y = 6; // bits are 00000II0
Bitwise AND Operator: &
This ociaioi iciuins a valuc whosc liis aic iuincu on only
il both oiiginal liis aic iuincu on:
int a = x & y; // bits are 000000I0
Bitwise OR Operator: |
This ociaioi iciuins a valuc whosc liis aic iuincu on only
il either ol ihc oiiginal liis aic iuincu on:
int a = x | y; // bits are 0000III0
Bitwise XOR {exclusive OR} Operator: ^
This ociaioi iciuins a valuc whosc liis aic iuincu on only
il exoctIy one ol ihc oiiginal liis aic iuincu on:
int a = x y; // bits are 0000II00
The 8hift Operators
Thcsc ociaiois iaIc a singlc inicgci iimiiivc anu shili oi
sliuc) all ol iis liis in onc uiicciion oi anoihci. Il you wani
io uusi oll youi linaiy maih sIills, you mighi icalizc ihai
shiliing liis Ie cllcciivcly uI.I.e a numlci ly a owci ol
iwo, anu shiliing liis ..L cllcciivcly J...Je a numlci ly a
owci ol iwo.
Wc`ll usc ihc lollowing cxamlc loi ihc ncxi ihicc ociaiois:
int x = ~11; // bits are IIII0I0I
OI, oI, wc`vc lccn uiiing ii oll, hcic is ihc woilu`s
shoiicsi cxlanaiion ol sioiing ncgaiivc numlcis, anu
wo` oIeer. Rcmcmlci, ihc lclimosi lii ol an inicgci
numlci is callcu ihc sign bit. A ncgaiivc inicgci numlci in
]ava nIwn, has iis sign lii iuincu or i.c. sci io 1). A osiiivc
inicgci numlci always has iis sign lii iuincu o 0). ]ava
uscs ihc wo` oIeer loimula io sioic ncgaiivc numlcis.
To changc a numlci`s sign using iwo`s comlcmcni, ui all
ihc liis, ihcn auu 1 wiih a lyic, loi cxamlc, ihai woulu
mcan auuing 00000001 io ihc uicu valuc).
Right 8hift Operator: >>
This ociaioi shilis all ol a numlci`s liis iighi ly a cciiain
numlci, anu hlls all ol ihc liis on ihc lcli siuc wiih whaicvci
ihc oiiginal lclimosi lii was. Thc sign bit docs not changc:
int y = x >> 2; // bits are IIIIII0I
Unsigned Right 8hift Operator: >>>
]usi liIc ihc iighi shili ociaioi BUT ii AIWAYS hlls ihc
lclimosi liis wiih zcios. Thc sign bit might changc:
int y = x >>> 2; // bits are 00IIII0I
Left 8hift Operator: <<
]usi liIc ihc unsigncu iighi shili ociaioi, lui in ihc oihci
uiicciion, ihc iighimosi liis aic hllcu wiih zcios. Thc sign bit
might changc.
int y = x << 2; // bits are II0I0I00
bit manipuIation
Head First Java, 2nd Edition. Head First Java, 2nd Edition, ISBN: 0596009208
Prepared for [email protected], Eduard Simons
Copyright 2005 Bert Bates and Kathy Sierra. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
appendix B Top Ten Reference
you are here 661
#9 mmutability
Why 4e yee rzrc !hz! 8!r|n]s zrc |mme!z||c!
Whcn youi ]ava iogiams siaii io gci lig, you`ll
incviially cnu u wiih lois anu lois ol Siiing ol|ccis.
Ioi sccuiiiy uioscs, anu loi ihc saIc ol consciving
mcmoiy icmcmlci youi ]ava iogiams can iun on
iccny ]ava-cnallcu ccll honcs), Siiings in ]ava aic
immuiallc. Whai ihis mcans is ihai whcn you say:
String s 0,
for (int x I, x < I0, x++)
s s + x,