Core Java

You might also like

Download as pdf
Download as pdf
You are on page 1of 430
> Laser Printout Color Printout > Scanning DTP >» Lamination Spiral Binding > Fax (No.04175-226372) Exam Results Teg Arg uueuNsiofy °¢ Ae>) NOILIGS HLHOIF 9 aS ener 30) payepdy pue pasiasy S c 3 © a S 3 a © 3 o 3 2 o a ey manutactures and selerstadingsch tee products re claioes as ademas warranty of Consequential damages in connection wa cr aiing oto he Copyright © 2008 by Sun Microsystems, Ine. ‘This edition is published by arrange Pablishing, Ine. with Pearson Education, inc. and Dorling Kindersley hove, no part ofthis publication may be reproduced, stored in transmit in any form or by any meas (electronic, mechanical, photocopying, recording or otherwise), without the peor written permissen of both the copyright owner and the above-mentioned publisher of this book, First Impression : 2008 Fifth Inpression : 2010 ‘Sixth Impression 2017 This eiton is manufactured in India and is authorized fr sale only in india, Bangladesh, Bhutan, Pakistan, Nepal, Sei Lanka and the Maldives. irewation ofthis edition ouside ofthese territories is UNAUTHORIZED. Registered Office: 11 Community Cente, Panchsheel Park, New Delhi Printed in India by Taj Press. Preface xix Acknowledgments xxv AN INTRODUCTION TOJAVA 1 Java As a Programming Platform — 2 The Java “White Paper” Buzzwords 2 Architecture Neutral 5 Portable 6 Interpreted 6 High Performance 6 Multithreaded 7 Dynamic 7 $6 Svaweieg aury-pueunuoD £6 76 sey snoukuouy pur siazijentuy Any 16 08 sdooy areuuuaaer 92 sdooy Zz —suowayes euoripuoy 1 adaarg x30}g u yonuoy 69 andingy pue Induy aL $9 nding Sumeuuos £9 Indu uypeay 65 one uaWND0G [dy BUIT-O ap SuIpeDy 4s lav ons ay 9S sur) apoD pue swag pod ‘95 Aajenby 20 Buns Bunsay, ys aiqeinuiuy aay sBusng ¥§ — woneuareouoD $s” sBuunsqns £5 Buns €S soddy poyerounug ZS Aypiesayt4 soreiado pur sesayuaseg Is 9829 Lg sadAy 2uownyy usangag suorsiaauoD Gr —_squeysuo pur suon>ung eonewoureyy 6 sioreiado asymutg, eh storeradg)veatoeg pue jeuoneyay ga | | a st oz siojeredg quawiais9G pue wewa:ou eo) Sy sweisu0 Se Sajqeuen Burzyentut yy soigeuen by adAy tayoeg ay Ze adh sep ay Ip sodA, wiog-Buneot oy sodk, sa83quy or sedi eeq 6 swuawwoy Of — weiBoig Enel aeluns ¥ SE VAVINISSUMLONALS DNINWYYDO’d WINAWWYONNS Le sijddy Suyuuny pue Suapying fz uoneoyddy jeorydesn & Sunuuny 1013 woneydw05 Bue20) wawuoaug juaudojanag paresBaiuy ue BuIs7, 2 SIH BunooysayqnOn, syo0} eurr-puewwo arp Bus 0g voReWouND0g puk a2snos AreIqr] 4p BUI|PEISY] 81 Wed uoRn2aNg op SUMS af ap SuIpeowwog quaudojanac ene aip Buyf1su) 1 SL LN3WNOYIANS DNIWWV¥DO4d WAVE SHE ees LL nef noge suondaauoasiyy wow 6 PAeL Jo Auorsi}4 WoUS ¥ £ usu] ay pue siiddy Enel Array Sorting 95 Multidimensional Arrays 99 Ragged’Arrays 102 OBJECTS AND CLASSES 105 Introduction to Object-Oriented Programming Classes. 107 Mutator and Accessor Methods Defining Your Owin Classes 122 Private Methods 132 Final Instance Fields 132 Static Fields and Methods 132 Static Fields 132 Static Constants 133 Static Methods 134 Factory Methods 135 ‘Themis Method 135 Method Parameters 138 Object Construction 144 Overloading 144 106 Defaul Field Initialization 145, Default Constructors Object Destruction and the fimlize Method 152 Packages 153 Class importation 153 Imports 155 Addition of a Class into @ Package 155 Package Scope 158 TheClass Path — 160 the Class Path 161 n Comments 162 Comment insertion 162 Class Comments 163 Method Comments 164 Field Comments 164 General Comments 164 Package and Overview Comments 165 Comment Extraction 166 Class Design Hints 167 INHERITANCE 171 classes, and Subclasses 172 ince: Final Classes and Methods 183 186 191 {9% Spowpayy s9ING Woy Sa;qEHIeA LeHy BUISSOD.V 99% Sess") aU |e207 9c janes {Auessa09n Ayjemoy 21nj98N S958e]> s0UU] xy £97 285812 sous 1 saymy NEWUAS fePDads 09% ares algo sse9dy 01 S5e)9 JOUL] UE 70.957) cz sesse|5 sau Sox 9RQITED pue saDeHaIUL 6 BuLOIDPA!GD abz 5988219 eNSgy pur sodeOU| Lee saoeyIU Jo sonmadorg Te sameway 1hZ S3SSVID YINNIGNV SJOVIMIINI 9 Z9g — swiaeg usIsaQ Z9¢ —_Ulaneg UISaq Ja}JonUOD-maIA-jaPOW yp pue BUS 196 ONIAS HLIM. SIN3NOdWOD ADVIBAINI AIS G 8SE SEAT jOReTMOT pue NUEWAS £S€ — ADURIOIH WANG LAW ay Gre stueNg snow we suonsy Bee sasseyDuaidepy PEE Jed pur yoo) ap BuiBuey> :ajdurexg HEE IED poyrew ayBuls e Surrey ssoust7 BuNe—: LEE S9550/9 JOU) IgA a}qeLO}HOD BujODIg 97€ PND YOUNG & BuNpUEH :ajduIEX #7 Suypuep awarg jo so1seg €¢£ — ONIIGNVH INST BET aouENLOYU 10) UH UBIO we LEZ apop Aemy sueu—D aUAA O1 VONDAYEY BUNS 9¢7 —aumUNy we 9elqo azhjeuy o1 1zz__s0sse)5 40 sompgeded amp azhteuy 01 vonDoyoy Suis, Z — suondaoxg Suiy>re> vo sola Y Ae 82D 5819 24 Liz omDayey SIZ $9861 uonesownug $1Z —_storeurbIeg Jo JaqUIN axqeUEA e URI SPOURaW. Liz Buxogoimy pur siaddeyy palo 01z —_Si8r7 Aesny mey pue padi uaamiag Amqnedwo> 90z —_-suaworg 1517 Aewsy Bulssa00y 0 SIs] Aeuy 2uaua5 861 pouroy buynsm ay, 961 POUPaW sense a4, vet eouense4ur pue Sunsa) Ayjenby 6 powpeWy sibs ou, Z61_—_sseporadng nso ayy FH oo BLE seu SuEdsiG OLE Ray JO} s1U04 FePDads Bus) 08 — 10}09 Busy 662 sadeys az qum BupOM $62 wauoduiog e u) YoneMUOyUl BuAE|ASiG 067 axis awely pod v BulmjUNAIG 062 satuadoig aures 8gz— autedy e Bujuontsog sez ewes e Suneary zaz Sums Bupnponut 182 DNIWWV¥DOYd SSIHdVID G42. se880(9 Aoo1g yo sapsodors SLzSeRKOIg Liz sasse(p s0uUl anes 692 se8Se{> sau snowAuouy = come Pattern 363 Dialog Boxes 452 ‘A Model-View-Controller Analysis of Swing ‘Option Dialogs 453 Buttons 367 Creating Dialogs 462 Introduction to Layout Management 368, Data Exchange 467 Border Layout 371 File Dialogs 474 idLayout 373 Text Input 377 Text Fields 378 TO DEPLOYING APPLICATIONS AND APPLETS 493 Labels and Labeling Components 379 JARFiles 494 Password Fields 381 : ‘The Manifest 495. Text Areas 381 Executable JAR Files 496 Scroll Panes 382 Resources 497 Choice Components 385 Seating 500 Checkboxes 385 Java Web Start 501 Radio Buttons 388 The Sandbox 504 Color Choosers 485 | Bordeis 392 Signed Code 505 Combo Boxes 396 The JNLPAPL 507 Sliders 400 Applets 516 Menus 406 ASimple Applet S16 Menu Building 406 The Applet HTML Tag and its Attributes 521 i Icons in Menu tems 408 The abject Tag 524 i‘ Checkbox and Radio Button Menu items 409 Use of Parameters to Pass Information to Applets 524 Pop-Up Menus 410 Accessing Image and Audio Files 530 Keyboard Mnemonics and Accelerators. 412 The Applet Context. 531 Enabling and Disabling Menu tems 414 Storage of Application Preferences 539 Toolbars 419 Property Maps 539 Tooltips 421 The Preferences API 544 Sophisticated Layout Management 424 The Grid Bag Layout . 426 wae EXCEPTIONS, LOGGING, ASSERTIONS, Group Layout = 436 AND DEBUGGING 551 Using NojLayout Manager 445 Custom Layout Managers 446 Traversal Order. 450 Dealing with Errors, $52 ‘The Classification of Exceptions 553 Declaring Checked Exceptions 555 19 9S BOL 899 sI0S YH 999 sisry Any 6591517 peyUlT 969 suoNDa}Io ayeIDUE) 659 -Areiqy eaef aug ur saoepayuy so1e10y| pue UOND2}I0 09 _voreuawajduyy pue sadeyatu uon2aijo-) Sunesedas 089 69 SNOLDINOD —-¢T Leg auIyDewy jenna yp ut uonewMoysy adj 210U0 1y9 Suryprewy adKy 104 siovaurereg «psp Busy, 0f9 —sol=uaD pue uOMDaYEY 9¢9 aumdeD preopjim, 969 spre2pM Papunoqun, ¥yE9 —sprEapYA\ 40} spunog adduadng ze9 S90) prep 0¢9 —sadAy suaUaD 10} saymy soUENTYLT 679 ainserg Joyy sayseTD jo axemog 679 52556[3 D040 Jo sIxBIUOD IS Ut PLEA ION ary S3iqeLeA adKL 879 sojqeueA addy ayenuErsUy OULD NO, 229 {e891 10N ary Sadky pazvoioure 979 sse19. ‘SaDue su} Y>IED 40 MOsK|L OUUED NO, yum 979 parenueysuy og youue: 929 suomi pue suon>insoy $29 @p09 Aoe8e1 Buy7e9 £29 spoyPW owoUeD Eune|sLELL Tz9—_ suosseidhg 2u9U9D Suneysuedy 129 aunypew rena atp pue apo auaUa9 Ez ‘gua1u0D 619. S9|qeueA 2dAj 104 spunog 919 sseI5} suaUaD aduuig e yo uonUyaQ, $19 wauUerBoig 2uDU9D e ago UEMA OYAA, P19 BuuUTeHBoy 3N9UED Ay £19 ONIWWWaDO%d D3NID £09 288ngaq e Bus, bes say Buls8nqaq £95 adinay SuIBBOn y 95 18 4U0D s98euEyY 80} axp BurBuey-) 945 8u18807 paruenpy Sc BurB80] 25g S£5 8ur8807 $25 suondunssy Zunuaundog 104 suomiassy SuIsp, ELS Buppayp s2}aurerey soy suoniassy Suis) 72s Buyjgesig pue Buyqeug uoRLassy i Les suomassy Buisn, 895 suoridaoxy Bus 40y sy 996 squawayg ape pars SurzAjeuy £95 asnesD Ateay ay 795 suondooxg Suywjey pue Bumompan 195 suondaoxy afdniny Suyare> 65g stondang Suiyre3 855 58582) uoNdaneg SuneaID ESS vondaoxg ue mony oF oH a Ea Contents 14 Object Comparison 673 Queues and Deques 678 Priority Queues 679 Maps 680 Specialized Set and Map Classes 685 The Collections Framework 689 Views and Wrappers 693 Bulk Operations 699 Converting between Collections and Arays 700 Aigorithms 700 ; Sorting and Shufing 701 Binary Search Writing Your Own Algorithms 706 Legacy Collections 707 ‘The tastbte Class 708 Enumerations 708 Property Maps 709 Stacks 709 BitSets 710 MULTITHREADING — 715, What Ave Threads? 716 Using Threads to Give Other Tasks aChance 722 Interrupting Threads 728 Thread States 730 New Threads 731 Runnable Threads 731 Blocked and Waiting Threads 731 Terminated threads 733 Thread Properties couns EE Handlers for Uncaught Exceptions 735, Synchronization 736 ‘An Example of a Race Cor 736 ‘The Race Condition Explained 740 745 The synchronized Keyword 750 754 ‘The Monitor Concept 755 Volatile Fields 756 Deadlocks 757 Lock Testing and Timeouts 760 ReadMrite Locks 761 Why the stop and suspend Methods Are Deprecated 762 Blocking Queues 764 Thread-Safe Collections 771 Efficient Maps, Sets, and Queues 771 Copy on Write Arrays 773 Older Thread-Safe Collections 773 Callables and Futures 774 Executors 778 Thread Pools 779 Scheduled Execution 783, Controlling Groups of Tasks. 784 Synchronizers 785 Semaphores 786 Countdown Latches 786 Barriers. 787 Exchangers 787 ‘Synchronous Queues. 787 Example: Pausing and Resuming an Animation 788 Threads and Swing 794 Running Time-Consuming Tasks 795 9a) rrpung trfo say gator pop wg sey uo st SME wal aN ‘ag josSegaeape eo Yoga saunas pea vousmc toa sen ono} EO inn 1 30 Uoepo yagi. OU ‘yoseinyy 20x ‘snopuna alow ye hq sou #84 Apps dorama we aeord sm TY ‘somos ageurBeun xno Aue 0 ‘x9praaid Uoa) sano wR EUORNE EN AYN UOReNAIORN ‘4p auo2oq prmowt 3219 Sem KBopowRp, aud pure aus ouray aup om asing a2nfasg £18 xopuy 608 xipusddy 908 amy peony, ofBuis ou 662 HOM Bums ax Buss sH21005 | Preface ‘ofthese inthis book Our goal isto enable you to fully understnd the Java language and brary. not o give you an ilusion of understanding, In this book you will nd lots ofsample code that demonstrates almost every language te focus an the major points but, fr the most part they ‘comers. Tey should make good starting points for your ‘We assume you are willing, even eager to lear about al the advanced features that Java puts at your disposal. For example, we give you a detailed treatment of: ‘With the explesve gost of the Java cas library, a one-volume treatment ofall the eaures of Java that serious programmers need to know is no longer possible. Hence, we decided tobreak up the Book into two volumes. The first volume, which you hold in Yyourhands, concentrates on the fundamental concep ofthe Java language, along with the basics of user-interface programing. The second volume, Coe fta™, Value I ‘Adeanced Features (rthcoming, SBN; 978-0-3-2391794), goes further into the enterprise features and advanced userntesfoce progranuning It includes detailed discussions Of Files and streams + Distributed objects + Databaoes + Advanced GUI components + Native methods XML processing Network programming + Advanced graphics Inernationalizaton JavaBeans + Annotations In his edition, we reshuffled the contents ofthe two volumes. In particular, muti- Uhxesding is now covered in Volume because it has become so important, with Moore's lav coming toan end. ‘When writing a book, errors and inaccuracies a very much ike 19 ‘web page at bip//arsuur.o/arejara Statepcally placed at the end ofthe errata page roe EN (to encourage you to read through it form you can use to report bugs and sug- _gestimprovements Pease don the disappointed if we don’t answer every query or ‘we don’t get back to you immediately. We do rad all email and appreciate your input tomake future editions of this book care and moce informative A Tour of This Book (Chapter 1 gives an overview of the programming languages. We explain what the des doand to what extent they succeeded. Then, oe gi ‘came into being and how it has evolved {In Chapter 2, we tell you how to download and install the JDK and the program examn- ples fr this book. Then we guide you through compiling and ranaing thre pic fave programs, a console application, a graphical application, and an applet, using te plain IDK, a Javarenabled text editor and a Java IDE. ‘chapter carefully (Object-oriented programming (OOP) is now in the mainstream of programming prac ‘ce, and java is completely object oriented. Chapter introduces encapsulation, the fast (of to fandamenta} blocks of objet orientation, and the Java language mecha s classes and methods. In addition to the rues ofthe Java ice on sound OOP design. Fin jim tool that formats your code camments 2 a set of hyperlinked web pages. I you ‘ace familiar with C+, then you can browse through this chapter quickly. Programmers coming from a non-object oriented background should expect to spend sometime mas- fering OOP concepts before going further with (Classes and encapsulation are only one pat ‘he other namely, inertace Inheritance lets y according to your needs. This sa fundamental tory, and Chapter introduces ting class and mou t programming in Java. The tin Ch. Once again, C4 pro en sor ran robin poe nfiy vena wen xounvo LX] aeons saennsinenea ar LE] iA “319 001 ey Sw AE a PBB EN SLON ‘poo sandunoo uesnida 0a edie oon a9n‘SYoog zandusos Ase ut uounuo s Sy ‘aenSur eae ap 30 spuom passasas a mad: axy rnoge fe NOK > am pul “-g ag wae UT Feap all e pup sey RexpeaRA “rR wonEZ MOPS peaNA Ma [9p 0} mou PUR sprARA da Sor MOA NOK MOS aL (Caredord e ui jonuoo 30 og # st peang y) Tarered wy auop aq 04 sys wreABOAd -ypo0 ad Apgrumusdoysiag eaef op Soyaser moge von osu sow 2052 side) 395 ION reotdoaaag enef ong osned sae Ain nai Gun Seana 9 sseBond dat "eye oo a0 ise sm yop PUES ry 2poo ofa fe Sue}> etm eo sour sy ‘opdunex se pes ae Gay AG UO st apeD ansn0s aso surBO er) ‘vostan po Suypaong, au aon 3,u0p oy sropear an doy oy“poonponuT seiA 393} ‘aR UPR Usoqum VORA ap ABM 304 TEV PED: 2uy-00jebyp a ut aso UA ano; sIOK a ‘zou iq € ase stoeDsop aso uOR>eS 34330 ‘wondaocap Areurums ows eppe 3m ‘SR Ys 9 305 soepoqy SqunureBorg uopeondaly 20 Cragg soa x9 anoge je wif 0K_aDeH Dp Josn penydes® unope(d-ssom ® pC OL of score oot Sg a, TBP Yea ut TON IND BuIMg a sassrO=Tp 6 TaIdeyD soejaud Dep Ea Acknowledgments ‘lowing me tobe bissfuly unaware ofthe existence ofall thse fli behind the scenes T am gratefl to Vanessa Moore for the excelent production support. My thanks also tomy coauthor of earlier editions, Gary Cornel, who has since moved ‘over the manuscript with an and saved me from many more embarrassing ents ‘Reviewers ofthis and earlier editions include Chuck Alison (Contributing Baits, 1C+ Users Journal), lec Beaton (PointBase, I) Cif Berg (Savvix Corporation) Joan Boch (Sun Microsystems), David Brow, Cocky Cartright, Frank VAY( OL NOLLONGOWLNI NY coo “eTBM 3a pur {esagsKsongy UN) wpUT] Zap UA Sniera % 4g} dvy9 7 pu] go ‘ensue La (oBam> ANS) 7 Sq SHAT Pe UaanRi RDS Hey BON ans naa omy oooh ‘Suausipamowpy er Thesst eo }rain 0 gett enncee neu ofectene et Inia computer os, uti Misingion es nt spec computer Ian smusing to revisit those heady times, and we ive you a brief history of Java in this chapter, Jaya As a Programming Platform Inthe first edition ofthis book, we had thie to write about Java avrg been a great programming Janguage, but tis probably to lat for that. Once language i out inthe fed, the ugly reality of com ot of lack for this paragraph from someone very high up at Sun Micro- hall remain unnamed, Bul, in hindsight, our prognosis seems accurae, tofnice language fearures—we llecon, and thei, but they don thave Your on if you want fancy graphs enero ood anginge high-quality exe ction environmen, nd a vat ary. Tat combinations what naken a ah iresotble proposition oso many programmer. The Java “White Paper” Buzzwords ‘The authors of ava have wien a nfentilWhite Paper hat explains their design soaband acempisnents. They alo published a shorter sumer tat sera long the flowing 11 buzzwords Simple Portable (Object Oriented Interpreted Network Savvy. High Performance Robust Multithreaded Secure Dynamic Architecture Neutel The Java “White Paper” Buzzwords Inthis section, we will + Summarize, with excerpts fom the White Paper, what the Java designers say about each buzzword; and ‘+ Tell you what we think ofeach buzzword, based on our experiences with the cur- rent version of Java. =) NOTE: As we ite ts, th White Paper can be A) eset surmary with to 11 buzzwords jeorevior La ‘Simple ‘We courted to bul a syste tat could be programmed xsl without lo of eo- ‘ere trining and whic leereged todas stander practice. So een tough ae teas unsuitable, we designed Joo as closly to C+ as pss i ‘onder to mathe system more comprehensible Java oni maa rarely sed, poorly understood, confusing fetures of C++ that, in our experince, bring more grief ‘ha benef. ‘The syntax for Java i Indeed, a leaned-up version of the syntax for C++. There isto need for header id not however, attempt to fx all ofthe clumsy features of Cv. Por example, the sy ‘taxof the svitch statement is unchanged in Java, you know C++, you wl find the rast sition tothe Java syntax easy. you are used toa visual programuning environment (ch as Visual Basic), you will not find Java simple. There is much strange syntax (dhough it doesnot ta the hang of), More important, you must do al more prograauing in Deauty of Visual Basics that its visual design envizonmment almost au “ides lot ofthe infrastructure for an application. The equivalent func programmed manually, usually witha fair it of code in Java. Thee are, however, ‘hind party development environments that provide “drag-and-drop -tyle program evelopment. Another aspect of ing simple is being smal. ofa is to onabe ‘the constructon of softarethat can rn sand-ah machines The sae of ‘he basic interpreter axed clase support abut ng the bs ta ard nd thread support essentially aselfeontsinedmicoletel) adds x ‘This was great achievement atthe time: Of couse, the brary has since grown to huge: oportions. There is now a separate Java Micro Edition with a smaller ibrar, suitable for embedded devices, desig ia technique for programing tat focuses interfaces to hat objec. To maka analogy with ‘carpenter would be mst concemed withthe chair “sunpeurjenutdv uo soras wasonerd xa sagoso mp wa WH aaRDaya Os uanoxd say ‘Boyes sy], wonendisoo ouy-ur3sol pope said e”apeo uRPeUr OR s>Uanag anbaxpos aes au poor uate eoseg ASIN aM Pues Jo woe oun poua0 5 ya sep OG OBE swe Og Ue BIOHY OPI ML PIOUS SAL “Ang w 2900 apt cp 9 pons Kgs pur aon us wo ino fo 24 pds a yan gsc uae 886 Sue ‘ay yong suo sua spose Bunzcaus8 fig sya sop amdiuos wal 949 Rs aa an ng fo susan gtd uso a 7) rea pyr le aya senpnpe ur mya ad 4, amen ampoerryouy “aor Buneasa wos sda pur suns se wopeaed 94 son 0011 esneoeg Xomy 1 Fu Ue pew MyroEs BuaNS ee ey BET ERLE 62839 [ue us:9 op ssopuen UND Jon Woy Bue "uupuED UBD enpasd UNO SCA. 0 sno ha e—uoca 0 e Kars ue series mis to eo TA Puoel xaMy Uo posegyosoN wey WUE ABHOR apr Buta ¥"ILON -sunpet mot vo 8eqaud ao ‘pemone aq ues seep ip ‘sup ap Jo souRNe ap en NOK au Ku “SOHN oy. AME ‘aque> nok ‘sep pause nT sume 208) sosep pouss AEE 30 voRU a ey eao[ [-Tuorraa ung 2m ZA waefo Poppe ug axey SamMyeOS INDIO. IARITN Y ‘soma pur snsos Jo peye uounroa epee ALUM aN HUNAN + so Sure “argscodin sppene yo spun ue ayeur 0; pouop sem eaef Suqueae 2p wos ‘qu uf ay pe feoyuypy A398 wo9q BAY ej OS PUNEY pon ee sna es by, pms 40 ys 9 Ba aD UO ssa sya afame sagem ay sagas funn wo pd ay sy syd 198 my pam, “sons peggy muons osm 396} pagan neal aumoag Ey re ‘erqunodam Spy choy useop yew) aseg Tenn a Sony © ny Ss eo ef JO ama SRA Ade ann. 29 Be sod vb poss urs faa sep ano ees sey oy auofive quod puosys ay 2 Sy “aurquna ye Kuo da mous Prnom SoBe Te, ao ur ap suoqgord Aue soHep mpduo> eae ay, TYPE Aa Ome St aATHEN| SNL, nsdn Bde of uo sta uo] fiaaog-ysomaN aavaio oom tert pin npr eee ‘ey ojertanuoour rt push tax ur ons UaaDsd se ORENRO PAA “+49 fo ou fos a 0 fo sac noel 0 5 eae py prom ond, oelgo-on, rae of pos, oop ay gin urpueces pus Sugpyng som 34 ‘exe{ 0} UORDMPORUL UY ML JORde4 Chapter 1m An Introduction to Java advantages. It increases security because the virtcal smachine can check the behavios of instnetion sequences, Soma programs even produce Dytecodes on the ly, dynamically erkancing the capabilites ofa running program. em define portable interfaces. For example, nnplementations of for UNIX, Windows, ‘As anyone who has ever tied knows, it is an effort of heroic proportions to write pro- _gyam that looks good on Windows the Macintosh, and ten avers of UNIX. Java 10 Inede the heroic effort, del Incremental linking has advantages, but is benefit forthe development process is ‘leanly overstated. Early Java development tools wer, in fac, quite slow. Today, the Dytecodes are translated into machine code by the ust.n-time compiler. users disagreed withthe statement thatthe perfor foday, however, the justn-time compilers have tive with traditional compilers and, in some cases, «even outperform them because they have more information available, For example, a jus in-time compiler can monitor which codes executed frequently and optimize just Java Applets and the Internet ced or sped Amore ropintatdoptnizatin the annaton “ang of function calls. The just-in-time compiler knows which classes have {an ovinlming whe, based upon te carey lnded clacton of classes a para lar function is never overridden and itcan undo that optimization later if necessary. Multithreaded (The bens of aetna epson an tne the same cross ma undedying operating» tne srs toy fit on cents Toco me pera ahora This san inp eatin owe son ia which code eedsto be ade nenngpoan A in ou oes Sa fm nding straightforward, but current versic : theseuctueand bear os eels reste ia ne ‘Banayz chee turing sch fava GUI bles cnt debuggers Pigeble Components and objet dbus JOU pe G66 JO 8 3094s (Hy HOY IS, ‘ypu prp ey undo» »adooe: axtdsuy ue a ono pot smyg waef oy owes paw hag > Sasa we jo UTE aap Sean YEO Ye pozseAs HE UNG gdoad NO St se AN 9 YEO UE J0 OO] HE POAT =H 25N0299 enue] sy 1003 PopHAP AsO. ,"pUua a OU POL ¥ ea selon apes Sug sejrogsed uy ose wey seypes ++ UO a8 srp poseg Ang os pumaxS5oeq XINN # wos skndD Taner | dood ung ea, wo} qosd wre inf panos Sun os ss se aupeUr pent 8 pe sovuti pofond wip x rmsta penn pet) auNDe ee wD Pom 9g yoanest gest St ay uso ‘paysrgnd omen do P2564 5 vase yo £20351 HOTS V = ae a Biggio pareoasydos ano sor ip a8ed gan: woo ag pu aide xp Supuacend, ‘pon apisoy wo see oGe ‘x03 sou poou nok ‘aun pena xg jo aysas oy OF Sue HUET FON ent 30 Cows Hous V nef 0} uonanponuy uy mL aadey Ea ‘Chapter 1m An Introduction to Java of the few things in the clent/ things we'd done: architectureneu- terribly impoctant inthe workstation ‘apsbilty and added a new event model for GUI programming, Itwas stil rather limite though. ‘The big mews of the 196 JavaOne conference was the upcoming release of Java 12, vwhich replaced thecal tovlike CUT and graphics toolkits with sophisticated and sal able versions that come than is pedecesoes. Thaw day afer () 5 tonD9p pay Sune da perm z ch nero adeapod moped ear corps Sond es e4L SUIRUNODP HOM, yr umes soo 920 suns sonpend ur yrjosn anos pe uerodur aro ove euresdoud ea sure pueSING ung 9g ue> sodde sung sures2ord ouoqe-pus are yooq sr utsurexBoxd a 30 60) saSed gama 20} 2po0 ay) aonposd og es fn nm nee EO si 24 puros sido: acl oy Pan «5 Sepoy Sasamory Mojs 001 ave suowEDM povured ae Lap aeneoag auediaymen ane ‘2m dima amen (emt, +43 20 ro Kags ‘suos w pue +49 0 prom Koy se wnef use JO S100 1, a ene ynoge suondaouossiyy uouNo omnes parop, u29q sy eaef yuIod sap ond wonnqmsipa: put bone>ypaut 1} 30x "uoqosdsu XA m4 axgeTAE joa sea sheaue sey sore ove pur aumypet yeast ap 205 poo AOMOS SHAT nou wBrsop ai9 pue sus adenBur jo waurdoyaaap avg uy saruedoe> ayo Sue soy yo 28am any 1996 ntl =pe gol np Kq Pap ‘smopuing 01 pag ate na 3 osuopusdopur mzoped pus Aguase soponzed a puro _umys poo aos yo ones “suas oaaqe4y4 19} 30g ORTaTOO Bog pur SUN Tenia 8 aenSe Sururnesoud ues sens ear wi0y Seapr poo ATE 003 4) eeos 5 snl “mgeeoe #9 Yn oN ‘sooons Jo amos ap rou are sos a sn "eel ts anppopoad ooo ues ses os Pa smuEG prey arom uy sump op Apseo nad] so ampnnseun ayndoo xp jo yar a “again ar any uk 30 nue eg Aq wet pena aos odds ap 4 Kagan aig Aq ator ae; pouruseyap sf enue] Fupunuedond eyo sss ag] 24, “jyssonons Apa waog ory 2109, 2 ypns ‘say notago ie eoSenuy seaoy ‘qusendod poavds ng SoBenSiey Surzureaxd 291 Jo spaxpunny uaog 946 019 ING aid sramuretSoad your eruyy Sumumarsfoad apt Sony SuruuniSoud sags sn anf “swf ef ena Bacon ozone vee pm 0 exef on eoyonponur uy wt sade (Chapter 1m An Introduction to fava rtbuted on cell phones, We must confess cen sthave Java application rrvigon cell phones, but the and screensavers seems tobe selling well in many mazkets, TH? Foranswers to common Java quostons, un tone of he Java FAG (roquoriy asked 1} poston) its on te Web—se fm. hued Jerre an- etre St ee eet Chapter THE JAVA PROGRAMMING ENVIRONMENT YY _INSTALUNG THE JAVA DeveLOPMeNt Kr YY CHOOSING DEVELOPMENT ENVRRONMENT USN THE CONeMAND-LNE TOoLs Y-_USNG AN INTEGRATED DEVELOPMENT ENVIRONMENT 1Y RUNNING A GRAPHICAL APPUCATION Y BUDS AND RUNING APPLETS wo nok 0) fda ‘ug -epuadap re rat DRE MRM PROT Si ws "ssf paubsyp ug uu pap uy a zea SSH ‘SoA9p es ao poe ‘stu p> uo oe) se eae ag an sear ong¢ eee sm 2aatoe aidaos 25 eaoped ea a one sending suopegdde meade ee sdooysepunamsojwaoped nea 5 von pepons 5 __* ips eid ean ‘onus cx saumsue 26 arenes eet Af eon augumy eef 9 XA Pae> Sipepuyo 51 "ajepdn ue sean Sasenef 2} wy ndEFasp og pepe sopra ng wn Ae 801 Sap onset DE jo UE UOKIDA eat] 49 Se union -Sayu0D eUManI0g "py eOULdOPAA ‘Paou nod yup areaujos exp 728 ue> nod amnjaq unde yo: nour fap Pm qoa unsn spear o post is nod yy wurden eal ng proqerop ey ar 943 Gurppopumog np andeurs exp £2 Bi Me oboe wf sere -as ta Bayes css hq 29 i > ans a Lo ua ear #6 sue pabopedaid ote Has aur ous ae {Sauopeid aso 30 ssopuon au Aq paancaastp pu pasunoy are suo “Ba siow ina ‘Sauopetd ayo fea pus yooauoe aq 0} eo WOWaD}Aap yosmee ‘srolra my uossg Swopuys poe xmUT SH"; 255 aeaDHN Ung ay eerone 38 Gra tor semadojonag ene ap jo suokae sep orn pu edu» sou ay aha qaomdoyeaog eaep o43 Suressay ‘endue) Sunmuesfard vaef ay, Sup “pordho oq ms no aroun ¢ sade 0} uo asous oy Spear 928 ok soo9 te Ea 1px wowdojanaq enef ayy Rapes ——___ nestogte a oesgantst EEE Wea, Setting the Execution Path ‘After you are done installing the JDK, you need to carry out one aditional step: Add ‘the jin directory to the execution path, the list of directories thatthe operating sys- tem traverses to locate executable files. Dsections for this step also vary among operat- ich is the Linux default then adda ine such oar of Ash fie Ble ‘Under Windows, lg in as administrate Start the Control Panel, switch to Cassi View, and selec the System icon, In Windows NT/2000/XP, you immediately get the system properties dialog Ta Vista, you need to select Advanced System Setings Gee igure 2-1) In the system properties dialog, click the Advanced tb, then click onthe Environment button Scol fough the System Variables window until you finda variable named Path. Click the Bit button (see Figure 2-2) Ada the ib directory to the begining ofthe path, using a semicolon to separate the new entry ke this: ibis Save your settings. Any new console windows that you start have the correct path. ishow you test whether you did it oa version gare 22 setting the Pt environment varshe in Windows Vita «sour pur snp vay e-PRO WANED, S9p ¥ Pou ae nd ofpaus fas yosonyy Sunn wy sion soya Supumtont oe ywournoraug quowdojoaog ¥ Bupsooy (axa spn ne mp9 20 (ee sous 0 uosuedo ye) eunoy WRLH w woRERBEMSOD Ae soap a ot 39071 ‘300 por opm, (open 14 yay 29 Se oa a) ‘ant Aioioanta EARP Zt OTL san Kopanp al ep SMo¥s 7-2 >1RL ‘wonenaumoop Areaqy xp init SAIsUapxo 20M c pSOU EIA ROA 3EIN0> JO“ ‘saumos eaef au apisut 380d 0 ae ATEUOISDO Alek nas "eae Jo suORTIOYEAD uetmzoo a TO “Aropanp ogee 249 0 28) wauuosjAny yuaundogaaag ® Bus00q> “sgn Simyaue ern ag te pew pom stay uy, Yaorsanp ap xp ont acu pie apy diz voneWauMDOp a1p PeopUMO “ped uognana 99 vos: Lops agri mg PIP PORN NAL OB AME MEH T sda a9 ons ‘Apng,-acyoen jeey 0} woRUeKERIOP 2 PEORLMEP UE NOK “yeifou oy aesedb 126 ony praezdiuo ei PeATE oo OREAUTZOD Oh, “ged vopeno og uns Gospel em pm FTES aL a HB EY T Suwoyoy oop dang Ye op of yx pusuranas Agia, 9po> somos. oy 52208 ABO os He PEC od pore 9fy poomudao> esq =u Pala xe Sqy soe Aa a ‘WoRDiuoWN2eG puD eosnos AumLarT ay CUNPISUL Response eye t= m/:E4 Se GON oe atic ate Sod iy og eng ey A) ‘wouonna Bopunediong ef od m7 onde Chapter 2m The Java Programming Environment ‘compile and launch a program along with an integrated debugger. The baste JDK com- fairs nothing even remotely similar. You do everything by typing in commande in hell development environment. Moreover by executing the basic steps yourself, you gain a better understanding of what the development environment does behind your beck, “Howveves after you have mastered the basic steps of compiling and running Java pro- grams, you wil want fo use a profesional development environment. In the last ‘ecade hese environments have become so powerful and convenient that it simply Jn sum se think that you should now how to use the base JDK tees and then you should become comfortable with an integrated development environment Using the Command-Line Tools {Lets get started the hard way: compiling and launching a Java program from the ‘commandline. 1, Opena shell window, 2. Goto the Crlantnk/ iit directory. (The Cretan directory isthe direc: tory into which you instale the source code forthe book examples, a explained in the section “Installing the Coe Ja Program Examples” on page 20) 3. ner the folowing commande: You should see the output shown in Figure2-3in the shell window. ‘Congratulations You have ust compiled and run yous fis Java programm. ‘What happened? The jac program isthe Java compile. It compiles the file Wan. jer nto the fie eae class The jon program launches the Java virtual machine. Tt execes the bytecodes that the compiler placed inthe class fle. _—_—_—_———_—_—_— fia] SOE foe ote ovr resis conptnng aaa tone for (ering g: resting) ‘on you pcbabiy use an olor vraon oto Java cere Java SE 80 fnvocueed aru ‘ert vry deseo fess toh Java programing language, and we ake ecertage of ‘hemi is book. you are using an cer version f Java, you need ore the oop a alows: for (int i= ie fa) Sten tinge cnmagtine ss ESE ‘Figure 9 Comping and running Welw joa ‘The Kec program is extremely simple. t merely prints a mestage tothe console. You ‘may enjoy looking inside the program shown in Listing 2-1 (we explain how it works in the next chapter). ‘pope wows youd ax-uonng {ondoyon wtpaand sea, page] dono a {S-comi os) we aea4 steno 19 oraap oi aura pie uy, se lad 9 eg wo og ssid Sore 19f0Ha Mow Pe amg agp ‘Anfie spot asdipa yp woisien nok fut suog ze ado Mn unr ao Sov eats soul “Gz amas) Sqm pez. ou oy soo eae, es -Z mae ag og oon ON ae ee Je ue Woks od wounuowstg wouidojonog poyesioya we Bap a iow @ wel fog 20 ‘iy eo) stoma tampar oy zeqando pe -Aedsp we sopra e906 wags os pt Aion fa ig ete aon To usea/sumog 249 AERA PAN.YO TNS 3 98" xEUPT/ INN pu SMOPETA UO 0M p -Goopanp a un was sya yup apo MP Preys rok wp xanfoumcy44 spe Use, sou we Guedes ey 5 "OTL seo 3OU PP oot ssepaig emoned uy smof aeeianoy ue aseazaddn 0 wopuayie ded nos ope puey Aq urerfond xp wrod nok yg ‘Swed Su moqoy ag oF voruone eg ‘smsor Sunes 6% Speo4 Boum 08 ue> sy yo raquane Auy “mopuim jays vt sursBoud Sores [ ovetnwepa ane ssoumuerdoud Auer sauresqans wosdoonsp yestajo aes ‘s7unH Supooyssyqnosy, wuowuuouy Buquures20i4 ene ayy we Z sade Chapter 2m The Java Programming Environment (6 Click on the triangle in the left pane nex othe project window to open and then icon the tangle next to "Default package”. Double-click on tela. jes, You should now seea window withthe program code (se Figure 2-6) Using an integrated Development Environment 7, ‘With the right mouse button, click onthe project name (Welcome) in the leftmost pane Select Run-> Run As-> Java Application. An output window appears atthe ‘bottom ofthe window. The program output i displayed in the outpat window (ee Figure 2-7), Figure 2-7 Running « program in Belles Locating Compilation Errors Presumnahl Ss oan 3 at hve ypos ore (asl fei ofcae, afterall) Lets sake of argument, that your code occasionally contains a sjax ere) Dy out ran or Be forex by Seg eee ee ESS anna Eee see eee nears (day uni < ga e009 wip pdu0D < gq 22049" (om pee (oxyqainy 60) se 2 1 ed 0 304 a 9 30495019 3 WO (fooponp suns a spy anes so atdnoo pagans 9) "uadoo agg aour i 20} y00r pum wad x wou ura pus ado> say sot ‘URy-aBew ue sigdap pur spe, suf ep anata op eu abuts ey weoad sg woneondde TWonided x aesuouep ps ou ‘pony Sua Agee owen wrsond OL LL wopeonddy wordy v Supramy “1 aide ut satnaep asdypa a som 2x, woumon payeson eur ngson jose # no a PNOKS SUORONASUT SELL sunona cameo ox angen ay on nyu] nox 7-7 SoA UO se BU edqoa wy sePeesom og Sz omBLE eH Toasn pue Iupsaioy wessoud snp puy nok ep adou ay, opwondée ramotqeSrar omy ZoroUM 6-7 arth ‘SB S1 ofa wore addy jeongdeap e Sauna, wowuoaey Sonawredorg evel YL w Z ToIdeKD ‘Building and Running Applets Eu Chapter 2 m The java Prograinming Environment eeusenrages Building and Running Applets ‘The fist two programs presented in this b va aplication, stand-alone pro- |, a5 we mentioned inthe last chapter, bout Java comes fom it ability to run apples inside a web browser. yeu how to build and run an applet from the commandline. Then we willload the applet nto the applet viewer that comes withthe JDK Finally, we will ds- phy tina web browser, Fist open a shell window and goto the directory Coreatoh/lc/Melcestgpet, then enter the following commands: most Wie want to show FOROS ORES EERE RK DEE RRR RSE E PETS HERE RE ERE ‘command to Invoke the Java compiler. This com- rebytecode file velco “or edeyD ur qapdde Fugu o8 eq aut0> ay soars et Soe ee eee ee eee ogo mow ey ‘Seung <-uny og os esd uo a4 wny Sy ony < ACH Ds Soeur -oapu otsjnap peau 20.0u9 0K SU UH SPETE UM Oe LED ma puss xp pur pemorg ai Ya DEIIUE Lowy Moy 98.5 SHIN e apres, sade md oy post nok nq wontos wr sa[dde Buys 305 poo saarana iad ‘u] “Ssonbas mos sarouBt 3 08 3Bed gam v eqdsrp 20 eur PUDs 0 SESED ow sey sanayaardeeag,"soaora pda aa ut S08 SuoTIng Ove 25a 3O KAN Fe Duo speaore w- o[dae yakdayomnoojan om Fureemy 1-2 am 7 s-gamBy on Bong oor af 3 Sinpunoains ay Buipapurre|dde ap speof 0 mney 25 plnoys nog Seopa the eR “quagamb au 20) 9 Yodo < HS raawoig mong “1 ‘gpm sap jo au om os as\eae{ sams yak sospeyd ain gin poston sees ay SuARSr -wSnyaeefan reser 4S “Worse isxe[ an peoqusiop ant sapde ‘pn rupees of SO 28) Due MMU] SOP UD eae suoddns wo}arA + “Gocouig esr uonemsneMorg a e}eUNHOFEA, urpanes 1 9p00 asoge add ox peo 0 mora sopdde om Su SHORPSUT AH PrEpueS O08 sono se NOS SE HN. “dpaxpins say 0 “6-2 Sumery en nojag tno area ung on0 a4 ep Jo SHMHUCO EL, = SSE F exef jo rau aig ue alps une apy GALA ue wesoud sen a8 0 poou oy 72(de “PI ap pa eI O Fas. pu ange Aenpe s woReog de ery 3A 395 EER ernie ‘weet Appmnb aok sa 49 af aR pl papnpur oo yeoads est werBoud se, pest UreiZaudsaynee payaso -ureoud wet akg UR ow op no SonaMoU >uER SUL wouuoan Suqunueidorg ene[ ay, w z sodeyD Chapter 2 i The java Programming Environment Chapter { FUNDAMENTAL PROGRAMMING STRUCTURES IN JAVA A Ships Java Paoceans Contents Data Tres aniaauss ‘OPeextoRs Sass Input aNo Ourur Conrro. Ftow Bis Nowaeas Arsays vate Aciotsteernaleletio( ea String ursting) PROPRRRE DDD OU SHED ER ESEES HEE O NES sarees Add dead eeasne In his chapter, you leamed about the mechanics of eompiling and running Java pro- grams. You are now ready to move onto Chapter 3, where you wil start leaning he Fava language. - jeus>siegpou ae ayo prong ag, 37 Kap oro F400 539, HON coum ursiosdany ee se ype) uonemgende w soynsna ve sperms 7 20 ‘aur sous; pur eng suoReLe Te Moa im sos ony ges a 0m “Suey a ps syqenoiion sung ox pou nos ei yap Sexpuods oe 5 uogogoods aber eer) enBir BT 61 EUENDY LOH itty 1, 25 208 IY, (aaidep pau ap ur spoxgous wake 08 Buns x9800 34) “pony oy way 9 pu sep oy Spouau uso NOK pp ‘9IN0 70 "IED NO sm soy sep ano 30} fy somes aku out ee ane FMM NOK SEE (UOTDEY 2oj ysods-cae{ sy ,poupous, aio aq) BeoxpuN MOK sx ay osu eee Sn 9pO ‘ap tpi ognoata eye sheue auneu enina eae{ aug “unesf03d pono vn (e806 “mopun 0510 2 09 980 —sa8y uso nod esfond ea oS A NOgS AESOP AIO! OT 5 ureorg wavy odung ‘rps da dep xn pear preys noua Ara xe eo pd A jE ‘Uy 86 Tens Se pas peg onnoue wots Seto smenelseNg ot mowing posadsTnarae ap s.r +49/.9 Uo men aNOD ydep eM ys syn deme 8 uo nos unseen +49 pound We ae nok Fee, sndino pu 0 Hop yore ean Syne yeu 3599 Ty vdDU vO PUI ‘sun fo}, ze saves sg sursSord Sus 9 danas Bunce oad yuan Supp jo eo8 mo wey Kee econ ye pom BUerON ee peng “in auc: popaou senbuupa au Sunpanuy ane Yo 9 pasa o puDdaL ‘3f09000 oy Wo FLOR 4, 8 IL aS A Sg ip Adams soynoae> resond op way, (VOR E>" OR BO 9 par ‘Snsst Aq wresBoad ap young Keung ayy amos tp se Aropanp mus par ss asians og epaoatdg xg Seumeu AropeutoIe Jado ear ‘xp ‘9poo somos ayy ut sod Aue peu jou pe ApauE> ay ays PaUTEUAAe (Cepayaesss) asm s0p—quepodta stase> ney) m9 oqo ay © uy 2poo sep ays yn nok ‘seg, ‘papuaddle we orans9 ag Ya HP Dagnd oi yo aurew ose umes 249 apo anos ax 0s eM a a ISU OF PHBL NOK (vse apu ‘Senuasajrsjes 20 ,ase> jour, payen sous 5 pao » Jo [pp ai Us seed jo asn sj) ‘spuou auf 0 Ypeo uy ana] aseatadc fenA we asm =puOH pn jo sjstsun> sure ef wana} aseosaddn We wp ues KR Sumou axe sous 1G 5 ess ame a4 UT MoO} 2m yptay) Uo UaAUoD BuTueu prepuEs cs | ‘wedioag enef pds v {ur proud ase sop sap 3d vaep se ups dono Suunuesfaud pag ai nok Mors 1dep OME HepenTe!S -exdnes ot uy sar zideap ws nok panous oxy sueioxd ces a UT ge senate insensoenBtesea- Ng eae] uy saanyanuyg Zoyuseadiong yeyuawepung wm € Fydey> Chapter 3. m Fundamental Programming Structures in Java a | 20} pos ep ad sapeterp ag avo ‘sd saqus gnod Sento “are ony soy senate aay 30 og "ea sal oyuead ye aw 92 porepop e aan ena aqeiea pio yey sous Sayer pd AS ‘exe[ uy soumponayg RunmurerBong yewwonsepuns wt € J9¥Uey) Chapter 3 m Fundamental Programming Structures in Java Data Types Ea For example, the result of dividing a positive number by 0 is positive infinity, Comput- ‘Tohily understand the char type, you have to know about the Unicode encoding scheme. Unicode was invented to overcome the limitations of traditional character © sencoding schemes. Before Unicode, there were many diferent standards: ASCILin the 1991, Unicode LO was release, using lightly less than values. Java was designe from the ground up to use was a major advance over other programming lan vidual characters. Most commonly, ese willbe character constant with value 65. tis different race Unicode cde unit can be expres as table happened. Unicode grew beyond 65,596 chasse- dition of very large set of ideographs used for Chinese, 1d Korean. Now, the 16-bit dar fype i insufficient to deceibe all Unicode pe sequences for special characters, as shown in Table 3-3. Youcanuse § |—\ss8 and \.D are the encodings for {and J ‘Table 3-3 Racepe Sequences for Special Characters ~ supph ‘of cede units. Each of the Chapter 3 a Fundamental Programming Structures in Java oe 7 | in camineterss* 17 y+ papers + OLIN: 1 ‘The keyword fis indicates that you can asignto the vatiable once, and then is value {scot once and forall Itis customary to name constans inal uppercase Itis probably more common in Java to want a constant thats available to multiple methods inside single class. These are usually called cas constants. You set up a cass ‘constant with the keywords static Fim. Here i an example of using a dass constant "7 perigt + LADO; aa method use tit oan pont computations. you tg [Note thatthe definition of the class constant appears cus the mn method. Thus, the : ts metas us set Hoabng pent computations ‘constant can aiso be used in other methods of the same class. Furthermore, if (asin out ‘he oy dts ae wry much eto the bahar ol th el ‘example) the constantis declared pti, methods of ther classes can also use the co ners resus are alowed to se an ete exons. ul ‘tant—in our example as Costas. OUR DOA {he loi chips supper tuncain of the mans wiheutns of peerance ) Thavere, Reo erence betwen dts and tit mode tha tc comptions may vero hen defast compu dont. Gre NOTE coro aasoned ayn sR Gey ond eying [Ey mistcstiattoracontan "your es glazed oer when read brotem that one enounters Bis wed inviotone ‘Operators Note that integer division by O raises an exception, whereas floating-point division by O yields an infinite or NaN result. poke us xg sen nos sequen ej ooz anmnbs np ‘op nos yg Suunserford jo pury ip wo Suspuaday pooy, -uojse200 eur no vey suonDuny eoneduaypeUs jo usUMAONSE uP 11g 0p 0 suraned 2g dn pring opaae HOM wou yo 20 ny ap OF WE Hq EaTYS YPN HO “agate wang yo onan nok ae 79 mood oedondde og yp Susy ou | opue'L sj vowenasada egy i 2 HG} A 1 © NOK ‘royrado way igen suossascha on autquton nod jt 3nTe xg soureuniap Apease unum 3513 ax paren jones aig “jdisexs soy Ayenbour soy joanpa a idan nop en nok Sento 20; 355 0 suyesodo eucyeas jo Hast (cposordan ws Apo am snag "> + poe 94 ea Pm ap jo aurev ag wana yy ano u}od sIIEy + ‘ose omeu si aBenSse +45 2tp sant Jon jswxn squuoy pode yoanqea a 8ueyp sreyesado aarp aerageT = s9SKED a ms o | Chapter 3 m Fundamental Programming Structures in Java Opes ynversions between Numerie Types often necessary to conver for one numeric ype to anther. Figure 3-3 shows the ‘The Java programming language has no operator for raising a quantity to @ power: You must use the pov methed in the lathclass. The statement sacha and the exponential function ands inverse, the natural log: Finally, two constants denote the closest possible approximations to the mathematical constants x and 4 ah we [EF] ema eas sao ce ance imate nananaiatnron EL} ancconsterts by acing te folowing Ine te top your cue fe ‘tort static jr. ag ath x Forexampe: syste. sare rove of YD Hs * » sre): ‘ouvia nj ep mp peanue a ou namsete oinpaadie uum» FD) ‘gon una sxoney{ neyeiodo Buc WB e EDep ty "r+9 20.9 MUN SION “*D "204 Poppe st (LOREPPe kp Oye Jo yea aH PNA) > =F @JOSNIEA aN SE adh; om 30 s2yqeuea aepop ues SC auervava “30g ues "Ts yuo soya perepe cope enum ur paused oe aged pen ote ‘Sssaqquared oj] -sojead0 jo ounpocoid ow smoys aed Surmopog 0 UO FEL, fiyosoua3 soypsedo pun sasoyyuesdd ‘rr awn 59, (209), “duo 04 ones umn # sx easy paroana ag mains ew wae: PQ] rt 24 20u2 igo nos esta oc 00 Jo AGU Ise 5A OKT SHOUD ee 9 voREUO;U 50 Som eon ae pene 192 052) (Gan) = (Gan) > — > weoT (ae pane Aunmooy Sseedo ‘ae uy Seamanaig Huywwedog jewawepung m € saideyD ‘Substrings ; ‘You extract substring from a larger string with the string method ofthe Stig clas, Foreample, ition 0 #9 position 2 is means from postion 0 inclusive to 3 P ania . 62s sitting ina common poo ‘Sting variables then point o locationsin the pool. Ifyou copy astring vanable both the Gcxiginal and the copy share the same charactors [Overall the designers of ava decided that the efficiency of sharing outweighs the inefi- | ciency of string editing by extracting substrings and concatenating Look at your own F Programs; we suspect that most ofthe time, you don’t change strings yout come are them. (There is one common exception—assembling strings fom individual char- Fst or shortrsrings that come from the keyboard a afl. For these situations, ava E> Provides a separate clas that we describe in the section “Building Strings” on page 62} otis: Computing the fength ofthe sub- strings easy. The strings always has length » 2, Por example, the substring "We" has length nas gonerly are bowed when tay See Java rine fre Ft of eng a araye of charactors 7 sesso to the string "Betidlea, (Note the lack sign joins two strings in the order received, exacly asthoy ae given) ‘When you concatenate string with value thats nota string the laters converted» | {2asteng (As you wilseein Chapter, evr Java objecteanbe converted toasting) | ements For eample, ing “Hep. Art even the most hardened ¢progammer lesan! than a sequence of tne cll Bl what ‘would want (and with thecorectspac- ne you change a character in an existing string. EF ou cannat directly change the lst positions of rst: make you fel proty helpless. B joaqed x annba sipperep Krejourajddns ays um apoo ase wate pam3:a nso so a, BUTpONES TLL SHR SH sores money 29 ne spear to nod sa, Sem soe yosar tsa SuaMr pue vere Krepwewetddey PAB 00453 92 a an preys nod ygaud sep pre ey Run 2pos pase aoe haan ue ngonwe oan a w SHEN p> Oo sr “sip 230 soe ye 209 yu eng puny at at mand pnd pun Na 2 sdoasareduno)—amn aia np, Raps + oyy swe PSA! aa se ius ou anes ae sss Buns 03g Serbo Buys oj osc = 9h pos no up pases 2901 sum bo 2 see sey pon ame soumquos tp soptsueg zsjm apo mage sary e BuPyeu ai eA adre4 4 enc ciuBieap mar tg ep uonano yao pan a8 seu Kubo ron “sue auesiu ei uo ue fave 2ue6 Bun Sey uoses! TEU, OTE BUS SoS By “woo sunt, eke som nu amg 2 pro WRLaND mK uoNsEd sey A]. su _guopt so std pdm a0 json ‘es a ur are sins ang uoneso| aes ap uy pao ar Bu 3 ‘sourus2j9p Ao a pnb are sin omy sagan 36} oy 3ye30d0= 3m woes ‘Sorgsaqun pur sy jon DAU uopssancho ay pox set ay ast no ate Buns ony aASUe IS OL Anyyonba 4of sSuras Bumsa, ‘e[ uy impnag SugouesTong jewouiepeng wm ¢ ID | re oo EI > sep avon span ve pr seq e001 = Sam es aed nope ewe 9p Pap Yous} Sep eam Nok seeped ave! ay ur pamep sep oso eso Mo Suman 9 108 opatesomosund ung pr sie pie ouus oman} Spe7-¢ Sm wade aqua joe 2uneoy Nau ap peas porous n> @oedzan up e peasy, seveds uejwonnuSrerynduy ng meso pouane ‘nde ap espeat pomaur ‘9 dae soy 3nd pea seep ses ap Jo spoupsu stosen 3 an na (-pxdeua u pepe wt sjeado av, po sojnayuco sso: Hormasi es n+ ns sr yexp sues onrpo> sy nok yd qosuco pes: oy ayduns se. veo incr prepurs, sy oy Suppeoy peste es ae fg ~woo ast) uFanS ndino prEpLES, a7 6) pnd yd oon ‘i amd mppann> a Sumd ng wou wy ndno pends -umy gonopod Sue mrertoudYanaMopy ne am Sunsa7e9 20} ng ¥am seer wippou ‘eimo9 jo yao wea nf Auradoad pend ydz>e ot vem am Dorsspa anor eRoud odo sno fe, indo pue ynduy “uque> yuo oping au se ep sures gyn BuEaS e smE — Es 3420 ZpIING a Jo SUM ap0>;0oqEIM smpung ns ua 0S ain “fs BST? Prunus na 24 spouper yaaa sour mo sou Lay Su aL _——-———____ srr "eoep eves 538 ps no es og Arenson ps 1 is021%9 etcuos pe Bs messed SS spina ay pan Suns 2308 ye nox pox Bua yg 95n o} ues 94 PRO 0 soponshoy se ons ‘nas s3.0ys wos suas dn ppnon senomon atu dts acauanon ea veaven gy [E] ‘ef wy saunnays Squnueiong yeauepany mE de CChapter 3m Fundamental Programming Structures in Java + stic Gale case) 6 [retusa Cnalecbject for interacting with the user hough a console window if such an interaction is possible, otherwise. A Casale cect s available fe any Be program tht islaunched in console window. Otherwise the availablity is eprint method from the linary. For example, the cll 8 characters and a procon of characters. Thats, the print ngepace and the seven characters rcsthe net lief nga Be rey ape parameter to print. For example: ms, Ne yar, Be A, “a ming y seep pur side ype B50 a4 sca ay Os ea ee> a Unk a NOT pouwe BS stoma mmeasrprraien srkoee ome azn mans FA] ey ooko Aree we 930 Kee une oj uosnina #0 on veo PO ALON, j -sstnuaned ue soguinsageau Gop pee ores dnd os ‘dara ead oe wD Woy 7 6 / ear ae RM MOMS 'sjeuy ‘sosedos di sppe Boy eunoo 2 oy MESON SE IGE, “dino paeunoy ag sauteed mp JOH pads wes nod wopRppe comme : j edi ogi pate manne ] o se4p] a9 jo au w Sypuo pu yak use eumey aD} oM} 8 nf BEEP Ere EPEC CEer ret eer ecareeapasee tudo 30 suopd Sumi ; 5 besmbisernd SSRN UY am RIED Pa no x os au eaeG a te epg 80 ak oy 9p, FS - ese Bae 7 msopey pa Reopen oqunusmes osu oy den $661 _Mogeogoeds mojad ay seamee aes eng Runspeaupie ome symm ys ea gs pox 1} BEI _fprreaigj ager oundie on paps sods ‘Rup Bes oe PEM h00 pur day "ese{ uy seunpys Supuedong yequowepuny w € Faden Ea q 4 Input and Output | «> | sa can soe in Table 3-7, some ofthe formas yield only apart of given date for is just the day or just the month. would bea bit sly f yourhad to supply the ‘Gate lle mes fo forma each pa. For that reason, 2 forma ting can indicate the {eco the argument to be formatted. The index mast immediatly follow the and it paste terminated by a5. Forexample, CChaptor 3 a Fundamental Programming Structures in Java _Abreitad weeky exe “hear tne noses i: ‘gt. rin 8H te, RE De, Be Foardigh yeni ding eo) a pins He Bw ae: ews, ee “ FF ieraivly youcan use the fig indicates that the same angument a inthe p> Fast wodig oie year tating 2am) a F coting format spectcation shoud be wed agaln. Thai the statement Falnentrane Ferry Gsm pint 8 He, ta Tet, rev) ae 7 yids he same outputas he preceding statement, Two dig month (vith nding 2208) @ ee ns a “Todi day thang me) @ EIR] tris acs coson win tea “rodigh ay witouthading 2) 3 Bp Youhave now seo a features ofthe pris method. Figure 3-6 shows a syntax agra x Fa weekday mae ee BE trtornatspeaties. a @ “Teg ay yee (ong aoe tren ae TA) eee ee 7 mis 2 mete | To igh har ith nding Zeros owen and 78 a | 1 axeoon ‘Nin digit rnossconds (ith ean 208) al BLY cecna coparatoris a ed ot comma, ses Moncay is omated as Montag Cu wll feels Yur how cule rteratoral behav your eppeations. i * 7 : “| Sascee k Todo (ribo nding ae) wen Dard d Poe Hep Ie pn! | Lf peain H gaint por | ee 7 Tire dgthnw viet ingens wee Tad? a | | i Tosi nie th deg) 6 F are = camel 5 Tosigt acids it ding 0) 2 lem 38 rormat pects eatax v Thedigt elisnonde i dg a) « o oC) ENTE: Arambor ef rmaigie we one spans Fer ang Geran ? > Uppercase ering eraeroon mart erase mesing or aeroon mater BEC Eramerc ot fom GMT z Tinea ‘Seeds sce 1970.0-01008000 GME a ‘Misc ne 1971-01 OOODCOGNT Taumiad Jo Levey num aseo oy Sui ue sop Spear ep Ee ear at apes mbemp a ga Satya ee ‘sdoy paouenpe FMCW eep ema, mein sony tea tor e201 oy uses acu oney nog 104 Sat Msiecteatarrcee tere ety prom ced ra oa doy pue susuize eonpucs, 8 sls onapjermy_ se 1pne soueu ged orogeny ti one Kobe ea py Lo suon nudauep pope oe PAO ao Bae ua, 4 od orn eee mn a oncioetn Dae ety ; ans et no8 0a oxen pe ogg ae “0 A bs il Et tne ied 22 3010 A poyonuco 4 Kona Bayes a ye FPO POLY orc yeu paving ea ens wo naty ‘din uss 9 eed toes Wess Somud uma prpnog 4 Sinn aeons adopt ee AR NH en = wo aR SB Aides duns opmsano ap op palo, ‘exo 220 I pe ALN oo us vocon pon vo, Poh "vas Preuubo ® uy tense ype) OO at SON BURMA BoD oy oy ap -__ Poaneep Aron oa Pm ha Bo yy ee SON ‘sels soimpnng Suerte easuepang we ¢ o> a Chapter 3 m Fundamental Programming Structures in Java canine ESM 1 eerr—ca'treetiog wi ine Dock igure 3-7 Flowchart forthe if statement Inova asin mest programing lnguages yo wil fen want exec mie TROTE Aton eonnines feds gonpaind dal slows yout Statements whens gle coon as ahs oe you tae» Dt sioed hat FE] NOTE. Hos conaimes ale a organ tener lows outa ave moe fave sgl fempl sate 7 Tener gent caer eg 9 1nthis code al the statements surrounded by the braces will be executed when youre {s greater than or equal to tage (see Figure 3-7). a (soma ont) 4 1/1 2030s sHDAORE 6g rady ( pugs 31,20, uo hs : oe 1 +e» sg Earn ep 0 sss emo opr poi8 apres 204 “6-¢ amy 298) vous: aH ‘poo 109 10H Puaces mp 0 SBUOIEG [9H 18 =) HOH) SE a _soumnes op omg, 34 35990P 9 I se -woondo shone syed 99 9g], a ‘mops onUOS ‘exef uy soamppnays SunoweiBoag jewourpung w ¢ soidey> Ea FE et 2 hse roping scsi : conto SEB ‘The program in Listing 3-3 determines how long it wll ake to savea specificamount of money fr your welleamed retirement assuming that you depesit the same amount of ‘money per year and thatthe maney earrs.a specified terest rate AABASAABSARBAARAReanonnnannnnst) plan for your stirement. We left out afew niceties expectancy.) 3 the top. Therefore, the code in the block may never be exe- ecuted atleast once, you will need to th the do/sbie Loop. Its syntax looks like ich is typically a Block) and only then tests tatement and retests the condition, and so on. ee; Aslongasthe wer ansters Wf the lop is epeated (sce Figure 3-11) This programisa ‘004 example ofa lop that needs tobe entered a last once, because the user need 10 Sethe balane before deciding whether itis sufcient for retirement. igure 2-10 Flowchart forthe wile statement REGHRMARRA RR HGR HAGE E eaef ur sounpnas Sumuwesdorg ewwouepun m ¢ saydeqy er cot [Although Java like C++, allows almostany expression in the various slots ofa fo loop, itisan unwriten raleof good taste thatthe tre slots of a for statement should only ini- talize tet, and update the same counter variable. One can write very obscure loops by Aisegarding this rule. you contrat etry yar?" 11 apace acon balance ve ws sn ready to eee ® t FRRSRURSKREBRSBEUERR ERE E BS ESE Determinate Loops ‘The fer loop is a general construct to suppor iteration that is controlled by a counter ot snvlar variable thats updated after every iteration. As Figure $12 shows, the folow- {ng loop prints the mumbers from 1 to 10 onthe screen — = —— igure 8:12 Flowchart for the for statement atement usually holds the counter initialization. The second slot ives the condition that wil be tested before each new passthrough the loop, and the third slot explains how to update the counter. “Evenwithin the bounds of good taste, much is possible. For example, you can have ops that count downs doo) 10) €J0 pdusers ods wsmous ce Bue] HO. + wp Sapam jag agiseae ‘dua 24 doo ss 5 oN 001385 saereeaedineennae | poe ages eee sup 0 // (Hee © 4 TT ize dot om aprane i sapap 0 2s 09 ‘doy 29 aptN0 doo yo ane pag atp 9 0 y4 MoK aio; “doo ap OPENER so yea a asm ous nok uaa © apr aren sup HON ere UL fon pop lil 1 // (os or “doo 29 0 poq 2x30 pu a ea Geo aos oy “wousgen any oy 30 of St a¥B UI aTgETEA WAREPOP NOK UNA, PRT POO 0n7'O6eSE UL saouRE IM06 UGH» 95% 69% 85» GF x05) OF aD LON 8.0} OS OF T SPAIN HR 9 spud ysmuz no pdurexo z0q “Gap » Furnas vo Sppo aw saind mojs joxU0 4 59001; {eat ¥"5d00 uy sioquns nod Bune oAenbo 14 Benn roe FyBIES Oa NOLS. ‘exe[ uy soumpnays SupumueaBoug equourpung mw ¢ sedeyD x" ee Multiple Selections—The svitch Statement “The fess construct can be cumbersome when you have to deal with multiple selec- tions with many alternatives, Java hasa svt tatoment that is exactly like the vith statementinC and C+», warts and all, For example if you setup a menuing system with four alterative like that in Figure 3-13, you could we code ks ike this: [Execution starts at the ase label that matches the value on which the selection is per formed and continues until the next break or the end ofthe switch. Krnane of the case labels mate, then the default clause is executed, if its present CATION hs pobre aratnes ogg you pao aavara EX] steven an strato, con xeon rm be rector! Tha aa lr ly dango ana conocer ora Fora ea we ne wee Sthaatenat ine poe “The cat labels must be integers or enumerated constans. You cannot tet strings For | ‘example, the following is an error: -aidurero ue 2247 oe, Sy -sopue souaus aig Jo s9peny af) yoRuCD sia NURIDGESamED a NALD se 4 ssn dooy soxeaaxy oy suoRpUcS ea Sipe Aa Adams yeu wean oy WOK oy zones oxy SywargWwaUaIeS weit ay OF TEL TUSUHSIES Ie ea eug -snuoouy erp sdooy poy amp Te Jo mo.Apof mao sean oj gem det nOK 950 eR ‘ur doo} paysou Adoop vaprsut suede pra SungatNo: Kypeve|seag Soo pa yds jo ano yea1q nok sj yup MALS yey PI # AGO Os WARS + BAU seamaqeye ye any saad erouurelsd aunoe = pasodat ‘sup prone og, "worm sp suena poysado ye > spe om Ap HEN BIOL IN. “spon ean sou pom 070 dun Ao UES NOK AG “aHaWEH EN -yoECe sn puss! yuop on KEEN pauE=N 9 Boon UED MeN ‘LCL ADH MAUR oy onde algeq3en spun exe OR e9eH Ue NOK pues aye EoRSn| Ie MOK ay ‘sam aaenEs YOLG a) eR ay say) 4 pote sp / tee YEG (wT) 3b } ee simon Houses oom J0 woweIES 3 ve UaNs wwewenRS hi Ogee URD aK HNC LON sage NOIR SI 305 anyen owes au poandiao> ancy pynoo nok 2s1n09 10 doo] ax Jo aTPPRA IB UE SIESDO 1205 =< 22920 doo ap fo doy ax 38 smv0 WE < 51K ZUR HPA 54400) aH HON, -so pa dor psa} pan aK MOA OKEES nen Sy >pota poi fo pon tad sour oan poses amp ny Peg cea a fussed yrs a0 fase /) (or 2 sia) at dex 20400 Joyo yeaug 0 Po 24 OR ID IHS B39OA en nod ae nora Bus aL TBUBIAS we PENEUM IA YOO 5 7] “apie Surenceaond ang yoda 9 sq apart ann tuaayee sate poppe asa pr pane sop ext TOgeUaN shop 0d ose ue J ig aU0H a9 51 005 as pEIAN Fp ITE oy mL og my ‘sg 2} sood pasepssuoo are outers ne exoued wT oBenSue mp wa! @pmpUt ‘enor ppEep dow lon phaione see xy ida eae jo audi aR EHODTY mou Jax}U0g oaLE DHL SMUIUEDIS | ( | fo “Tas 215 a 0 po 8/7 TH 250 ‘uopooe a pomoyyy ag sts ose 3 e019 04 HEM OA yor J0 me dooy Soma aM AIDA 4304 ones ips tp my poonpop 6 ype] \pee UT og MBER 9p Jo SUE mua Jog] RENN SHON HOM ye UEUIHES Yeaag yp seoys ew a_dUIENe ue SANFL {Aud ou past nod syamtos payesouanus spss UBUD pasa 28 OA VAL Tafa Sapa Tomo ema we RD RE FE cn 9s sett rpg ssn scnmies EE ? Is chen the contin statement jumps immediately to the loop header, skipping the remainder of the current iteration. the coins statement is used ina fr loop, jump tothe “update past ofthe fr loop. ‘For example, consider this loop: er (cunt = 15 cnet 8; cut) ts ct then the ont satoment jmp to the cant statement “Theres also alabeld form ofthe cts statement hatjumpe to the header ofthe oop woth the matching be. ———— Teas pogannar tae We and cata rt conaing, Too | BE re Seen cpuar yo cansmeye ees se ew nb rok nore ek or oti Big Numbers [the precision of the basic integer and Soating-pint types isnot sufficient, you can tum tea couple of andy cases in the javamth package: integer and Bgbeciml, These ‘ze dases for manipulating nambers with an arbitral leng sequence of digits. The iglaeper class implements abitfary precision integer arithmetic, and Signal does the peeeeueaereneees (emt pr) sms me SEO sp a eet > po ar pun pogo pus og pon Seba eae ee ‘hor og ane myado mony om roy fe ene grams aoc pa anes sae Ao ronan SMH ‘oy worgppe aie esem dooy sng ing "pera se aendur| eaef ag wo stulisop ay" 0 sam seo woaezepop ain stacy yds og -aueu gga hess in pae—1) Aa Pomonos ad mua xp sr yoryo—ads fens xp Busjoods Aq agen Kaze UP IEP NOK 205 1 2umyoq Jo z ade wi aDepNET aeEMT NB PUG INA pememnaachaentadin sti uso dear sono ays} se ons oes ean aX SDA pine {belo 20 fesse won ps oe 3050") Noumea sino AG Pe uoRoop> ogo aDfo YO Ol IAEA Wan 2 oe ecm (80829 + aga ny oop 3 pr, “nea apm a sy «4 Snaey mex (sins 7 soHDOIO aK Se fos) AEE UPL URNS es ‘Bong doot or nas sone yg SnnsuE Hundoy geod ¥ ona C3 ‘snaSauryo dew we st 7aqdurexa 204 “rp 298aquF Ue Yang anges PEAT pe seve no ad aures a jo somes jo uoRDoTOD esaioke AG AMINES HEP es HEATLY s2ydurexs 29 "pi Sau 9m ‘Gearewe yo setae “vondoxe spun0g 0 ro mapy, ee we ‘wr amon wend nada -ovoie agnor dn) ott Pg] Tuoulje og se4a0e ofA USI PUP ste GOL LE UE NUSLGD NAW NOLLEND xen anya sso sou 81g v summa (x 60 . “ssyurtpo smear aanys0 soy 51 sonar Sq ong gaqnsas anne au e-soqnstenbo 2983p (oa sb oo] vSusn a aidurra 2 eu we saa ‘pran s ess an 9940 {O01 ©1190 PA) 65.0 0 mo olga are Se Ks eecleein sd en ca sat ar san iq sg jo sopureaar pu juayonb “apasd “oa (Gn oda un sono fgnou esneoog oss oi 80nd OL S04 eT ION ‘em tte marco tanse nae wt nin 2 sheny ef w soanpnns Sunuwedorg jeuowepuny m £ 201deq> Ea Seasons arietleeertn cman aeliareier ee Saad gape IDL adnan yazan process all elements ina collection. However, there are stil plenty of opportunities to rou may not wart to traverse the entire collec tha rays clas, Te cal ray tasting) retoms a sing onsing trclosed in racets and sparated by comers, such 35°12, 3, 5, Ty ‘xray, simply cal Systn-et rine areas tStinale) Array Initializers and Anonymous Arrays shorthand to create an array objec and supply inital values atthe same time. “He's an example ofthe syntax at work: ‘a ies = (2,3, 5.7. Me BI Notice that you do not eallavwhen you use this syntax. ‘You can even initialize an anonymous array: "NOTE: etagal to have ays of ong . Suh an aay can be use if you wile & {A meron tat computes an aay resist anc th es happens ibe empty, Yeu const ‘amayoflngh Os a lone Tel) Noto that an aera at tngth Os not th same as rl (S00 Craptr 4 formas inormation about) ne) copiers «bray. conf Cuchybers, Teciabers. eth ‘he end parameters te enghofhenew aay A.commen we of is metodo Increase the size ofan array: Tacyers Aras. coyofCuckghaters, 2 + Weksinbers. lengths ‘The additional elements ae filled with ifthe array contains numbers, fils ifthe arcay ‘contains oes values. Conversely, if the length is less than the length ofthe orignal array only the initial values are copied. CA eee eres puliphesian eivailieniecrayeany Ef dnmnieelindrmpliateerranel nase E Figure 5-16 Copying an array variable For eampl, the following statements, whose results strated in Figure {wo arrays and then copy the last four entries ofthe frst array tothe second ‘opy starts at postion 2in the source azray and copies four entries, starting at position 3 ofthe target. “vores so po an seys0u Lay ous UY OPMENT a ep Bese 0g spowjous souoruanuo>soijo [e908 saptactd ssep Hes UL SPF EIEP SOW! UO EATS ‘Eran 9.0) poste 346% BAAR HOSAPIND 2 Jo UOSTDA PAT net /) ores 0 “seu deoy ou vo pourooge fae ue eed © oe oes a e080 ‘yas 962 04 Aur +49 8 Dy WIRY Be AE IEP BION +40) ‘ap uo poypeds wound ay Aiowre ‘Smeypu sourced sy soyouered sie iAzne] su eos ain poyeadas 9Sezze pao jo3[durex2 900 vaps pease 2864 BOK suaqoutDsed OUyE PUDUIUO srindino y a= "ene] uy saimjanng Suunueadoag jwourepuha m £ sydeyD a ee ee ee “The program in Listing 3-7 puts arrays to work. Ths program daves a random combl- {ation of numbers fora lottery gaze. For example, if you play a “choose 6 numbers from 49" lottery, then the program might prin et the felling cnbinzion TT] mike you eh! ? 8 » i 2 | a ‘Toselect sucha random set of numbers, we frst ila array aiers with the values 1,2, “The hitheasin method returns a random floating-point num * (esclusve). By multiplying the result witha, we anda = 1 number at that index Inially that s just + + 1, butas Contents of the ners array are changed after each draw. = amber: [Now we must be sure never to draw that number again—all lottery numbers must be ‘istinct Therefore, we overwrite saberse] with the last number in he array and rede = mers = Us “The points that in each draw we pick an inde, not the actual value. The index points Jato an ery that contains the values that have not yetbeen drawn. ummbers, we sort the result array for'a more pleasing output: acvcray of ype Ye rs, a, stn, a, cre _aidurexa 20g ySmouo ajdins 51 one ut Aes euors.1 2190 10 i yo sheare qe ssapuning -ypret saxapin Seqpuodsatos ve sqeounye ong pure Mpa aus ap aaoy sfeaze ap lana sumar eax ypu (aut 20) Aeaze euoqswoup-ony © w WOREUIONLE en aso} UE MU “ae ‘va. aa "es 0 BAS ereItE wR «LORE oewse weve we exes ot east nyo suauDpap seadh ames a core ome were ware Ome aan au 20 oer econ ts618 0 exeeeir svwcet ws a wrong ‘alg ‘09s en wy aK Jo Aerre ue ene save Stree OH IIT en ae Ree ura _—_— HERE con syomranp an odiyuns 97am ® wera Fawn aeor _ecootn —weRYE_—woeth ‘eampoyepnaapenn wsct ami were wwii «wie vies Cr a ssopmunang ‘pauos rosy 04 paswsut og pINOGS Axprpsze ods. st mamas} area oaeBaure eUNIaNNO "pEUIAL =u 8 ‘PUND} 5151» BBE 9p 309 YATES OF 8 (32d pany fu woot mondo pwANTOE 28s 20 ano 9p "es oH 9A 0 he unre pred sy sorounypnyea ut sore jo uaizjenat ue up Mog EMOUS eK ge ® aU 03 yueA nok asad vwsyuetpaun aBexois sy oy poe asry nOK UN, ‘vorpee snp doje Ayes uno nog squsursSueze x9 duo> ax0u zy) ue 524420} PIR fre Ao swuowiye Kez ssooe 0 X9pUu v0 WEN a80U! 36m AEA UOT, espouse -umquodye posi pou» Suse ear ay 9205 ‘| (e {ssi pio sams + -pardoo are sanye abn, enn 2x9 Kuo “asa IR SonIeA 351220 0 YH popped st ansat aKa sfivary PoucsuowIP RIOR aa -B ue 108s ssa deo ay OBL ‘atin, ‘doo oy sawp yo gum sane ‘ones supunye Adover soya o}xopurSunmsay pre. otnIa papped sar gp ato Yo ‘ang see 99 Ae ‘@nisnpx9) xopUN SUID aA po “(enssnpusepur unm oy ues sg79 30 | soap Apasurmde oy aon go “so, ta 0 ABLE UR e sepunueg sy eyuunay savd0> poraeeiien oe plo 288 [omens - ps 20 iy 4p tp] 0" ge ay ues ou Jo Kez estar z a ‘9 (92 a0, "ums 9c 30 eat simpmas Baoog oRpINS we TD Woes eens ashe ron anode yal youtie wh lt mn i a hearray cements, you can uses shorthand notion fo ink ultidimensional arrays without needing a call oma For example: cess woojuowpom y 9t-e omit ami 29) sraqumu uyod Speoy 29 30 Keane we 84> arene ean Kove dae apd mag deus dene wea nok ajqseaoe Aen ear yap 0 Ano tpt axp on scar atgen an yo mon Loup tM Aessogne Up a oy OX (y]sDm Ls LOTTE ML, ‘shea ro “ Ea wv ‘ref w sounjonng Suaumeliong jausuepund we ToVdeD Ka ¢ COVER RER ERS RUPE BREE ES = a} ‘Youhave now seen the fundamental programming structures ofthe Java language. The next chapter covers object oriented programming in Java. gpusrea Kama 99.09 sce acs ya omen “9 ua = . puso anof Suna 3238 op nok way, 1 JOO JO AUR} BNO wou algo ue jonusueo no wa¥My SOAP>RUDYR SPIOOD: eseep inoge Supqung9peia ae aoolgo wg oxy yurdenya 20 pepsin oxy sep 1 saenpard 380399.0} JOO axe pany an pre, povedar any sop 25 00 2) Sere ord pon 2319159-300[40 04 woRINpoNET He ogni ypu 35 rou Broa eS nn pe non sme ae sa Jo sus ion pos Ps A -oSerdue ont vooiog ssa not are asp Sana OR O9 Bf syenaid nade morned ng aidep mn siomneoad +43 paououadea 103 se nay af 0 sean koe 2 postop Hod ana fs ate ous wont gy sae empanend yup yn 90 Ae say essay Sued psouoroeio moge Sunray Ayan mide skh Bes or oem pe nos Banstredoad poysnuonolgo ws pumordyseq€ an OP OK Sossep uo mos 380 5 MOROK MOS Pov se ‘eae{ prepares a1p uy sassep 0} Sunpaq ein sialqo awa ue> nok smog nok MOGs « ‘Smaunited pso paaporne arom samen Seppe nena + ade cE Buruuurestoag parusug-Palgo o woHanpon Chapter 4 m Objects and Classes Nossa rvs ems eo oer, rds shoe. ayant ‘nce. Se the next chapter for deals on inheritance. Objects ‘To work with OOP, you should be able to identify three key characteristics of objects: -2 rule of thumb, and only experience can help you decide which nours and verbs are the important ones when building your dass. Relationships betuieen Classes ‘The most common relationships between classes are ea family resemblance by supporting fined by the methods that you can cal. ips easy to understand because s concrete; for ‘rample an (rer object contains Teen objects. Containment means that cbjects of cass | contain objects of class & na traditional procedural program, you start the process at the top, with the main func- tion. When designing an object-oriented system, there is no "top," and newcomers 0 ‘OOP often wander whore t bopin. The erswer , you frst find classes and then you add methods to each css. A simple rule of thu in identifying clases is to look for nouns inthe problem analy- sis, Methods, on the other hand, conespond to verbs, 3 For example in an orlerprocessing system, some ofthese nouns are tern Order + Shipping addeess + Payment Account ‘These nouns may lead to the classes Ie, Odes, and so on ‘an see an example of such amin Figure 4-2. You draw relationships as aro¥s th various adornments Table 41 shows the most common UML arrow styles. atte coger ee Suns (vam A» Ey aro papnnsan> vonuasard 2up ‘341 J08up ‘parma rapsU09 0Y, 318] POTTED SL SSEP deg 1 ours ay ancy seme s1OE NI soneueg En aryeconeme ‘SBS5eE pue saIGO wy aaideyD Bat | Se85e > pouyeperd Susp DE oe sw rst vingrecdesce EEN In these two examples, the constructed object is used only once. Usually, you will want tohang on to the objets that you construct co that you can keep using them. Simply store the object in a variable: ate ict «oe Date(s igure 4-3 shows the object variable bitty that sefers tothe nev constraced abject igure 4-4 Object variables that refer tothe same object nacan explicitly set an object variable to ml to indicate that t curently refers to no rend “Cos NOTE: Hany poopie rstatonly belive ha avn object variables behave tke G++ ‘rence, Butin Gor tore arco nl eltences and erences carol be exsigned, You va coe varatles as analogoutt oboetpanarin Coa. For example ‘You mus st intlize the éilinevasiable. You have two choices, Of course youcan 5g inal the vatiable with a newly constructed object desig «v0 520 (0+ you can set the vatiahle to efrto an existing abject. eae» vir [Now both variables refer tothe sane objet (se Figure 4-4) 4 Jtisimportantto realize that an objet variable does’ actually contain an objet. hoy riers to an jet Inova the value of any object variables roference to an object thats stored else tvhere. The tum val ofthe a operator sao a eference. A staement such a3 ace deine = en ates has two parts. The expression tn Batt) makes an object of type Date andi values ae ‘rence that newly created objec. That references then stored inthe defi variable hing fale to place. Ot course, a fae pointer srt cat ex The sya lst tho sme in C++ a biel The eauvlet ofthe Javea eernce isthe Coe LL jects ve onthe heen, When an object contains anathor obec vail, tat ver. les contains usta pointer to yet ancther heap jet. Chapter 4 m Objects and Classes zowyyeeeperepseeree infor, Set las, a seen) ‘he given date and time. ‘the year ofthe date the month ofthe date. Ths value is O-based; for ‘example, for January ‘he minutes (betwéen Oand 59) the seconds (between and 59) ts the value ofa porticlar fed. ee > | the year ofthe date date, This value is O based for the day of the month the hour (between 0 and 25) the minutes (betveen 0 and 59) the seconds (between Dand 59) sid aso) [Sis date arithmetic method. Adds the specified amount of time tothe given, time fl. ‘add 7 days tothe current calendar dat, call «at Calendar. O60 90, 7) Paraniters: field the field to modi (using one ofthe constants documented inthe et method) swat the amoiunt by which the field should be changest (canbe negative) ‘ sof) ‘ofthe week in the locale ofthe current use, fo example, United Sates. the given point in time, smatrs: tie point in tine + ate geting) fs the point ime thats represented by the carent value ofthis calendar gets the names ofthe weeks: ‘weekday snd month constant cera nok amos po slg mad nu a sens oO SL NP ne apes BE Seee HEP, nok ing apy anos © EHD: phew yes 9a Jo aE nwayehs posted e Sumay a fq poem oq nyBiur wg soe sla ve Jornysr9n“peuLdLNS Asan Busmoroy tp s9PISUCD seep sepa a aa yexp sure sto porous erst] zaupeds 008 [Soup = pe SEE sf dey 2 SOSSEP Om JOSE? Os "oemauediy 24 0 uoquane som Bx pe ‘puoonpau 9a necro vou oa seberanos ten yous seg aseuag wee [7A] "outa spo at pe Su Se 8 0} Xo A LS YEA OPE SIA BION ee anes ina sane ans ai > a okey due pee droge wore pene "pve fq hae speedo peo 258301 SED : Leite ? aunysrag see of eae[ ut uounayep soe e oy my edu OU, ssp]0 miolde UY, _sr9lgo afojdiao song 1" cuore use 20,8 3XB SHO joy ey eON595 3 HERP: jeg wredoud seep san jo uOeaUay SE EOP [cx | “FearepD UMO ANA SUIS Teese pursnalqo wf saidey Ea ontringvoromcuses EES Chapter 4m Objects and Classes | Benefits of Encapsulation let's lock more closely atthe rather simple gethie,getsnary and gethireoy sets anew value forthe star instance fed in the objet on which this method is Invoked. Consider the call “The riseStary method has two parameters. The fist parameter called the implicit parant ‘ter, the ject of type tgloee that appears before the melhod name. The second para ter the namber inside the parentheses after the method name, san exit parametex “As you cance the expict parameters are explicitly listed inthe method declaration, for ‘ample dole bjfercet The inpliit parameter doesnot appearin the method decaration are obvious examples of acessor methods. Because they simply retum the values tance elds, they are sometimes calle ld acesors. ‘easier to simply make the mm, salary and birt fields publi, instead of having separate accessor methods? “The point i thatthe nn field isa read-only field. Once you sett there ino method to change it Thus, we have a guarantee that the ame feld wil pted, isnot read-only, but itean only be changed by the risSary method, ‘should the value ever be wrong, only that method needs to be rigged. Had the salary field been public, the culprit for messing up the value ‘ould have been anywhere ‘Sometimes, it happens that you wantto get and set the value ofan instance field. Then ourneed to supply three items: + Aprivate data field; ‘+ A.public file accessor method; and + public field mutator method, js alot more tedious than supplying a single public data field, but there ae consi Some programmers prefer that style because itclearly distinguishes between instance fields and local variables. never be: ode onside fe ase HW Cy, oot 30 benefits t you can change the internal implementation without affecting any code other then Finding opportunites fo rime complet watches for cals to methods tht ar shor, com ddan, and opines thom ay caplet isle othe enainder of he program ooo fue o sane ayn 0 6:08 Ue paUe ¥ : Ee se 230 oa fan et 2 so poxgaure pue aoa 2d alg we ag sossnce ones Suxsudins ou st opRy ie ‘ip eeu yo Ko © ums oF paRU oA JaNoUEY RD Ben Kem que OOF SY p09 aidusera 304 50 unsadins puy2idood faew json 980008 ED POXBOUEEIOLG MOI soBoniahid Ss000y posvasstiy neyo wep area a ‘poyonusr i upigsr Uo Baloo 24140 rey evep ajgeaaea ¥ oy souorapas Berean G-¥ amis :epoe ara Buwoya uy sepsu0g jonsInsdeouE OM SEONG HL i Haq ang sd ‘ equ was seayaa8 pes waar pau konica aa en oop sitn ov angen FX] Eig oper eoanopr nrg pou msec bm Os NOLL ‘ove 850 sonau st hse 2 "up put #1083030] Bop o poou Aout ojos yey PUR 7652308 261909 J sep mesno wy doy EZ Sasse|D uO AROA TUBE, osinngroeromncises BES Chapter 4 m Objects and Classes sets anew value forthe staryinstance field in the objct on which this method is. Benefits of Encapsulation Tock more cosely atthe rather simple gti, tila, and getirefay ng geal) “The raséary method as two parameters: Te frst parameter clled the impli param ‘er isthe cbt of type tape hat appears before the method name, The secend param ‘Ger the uberis the parentheses fe the method name, ian exp parame ‘ae you can se, he expt paracers are excl sted inthe metbod detaraon for ‘ample ashe erat Te lnpct parameter doesnot appear inthe method dedaraon. ers othe mpl parameter If you ke, yo aanple of accessor methods. Because they simply return the values sre sometimes called field acess hod? isa read-only field. Once you set it in the constructor, ‘Thus, we havea guarantee thatthe ae field will never be corrupted. “The salary field isnot read-only, but itcan only be changed by the rissulary method. fue ever be wrong, only that method needs to be 1d been public, the culprit for messing up the value debugged. Had the ‘ould have been anywhe Sometimes, ithappens that you want to get and set the value of an instance field. Then youneed to supply thre items + A private data field; + Apublic field ‘A public etd mutator method ‘Thisisa lot more tedious than supplying a single public data field, but there are consid: rable benefits, Fist you can change the intemal implementation without afecting any code other than ‘he methods ofthe class. Forexample ifthe storage ofthe name is changed t0 polo fe osamivo syns uy es0008 uo pa stad ada yo eo uo jo spiny rented og sn00 oh pared 55 yo porpaure pee 2060 df 50 v3, 51 =n 55839 bag sossone ones] Sunsadins yous YPeY ep ain 20 doo © Uo: p9BU NOK JraveKR |? SN SEM GU sad ag $5292 UPD POM i vo 2a{qo ajo ep avai irceets cinciaga even ccimadessanestaitgitaremne patentee re icatareaearereres EX] Sasse[D EMG an04 BuNNEG, ‘se85eID pur spalgo my srdeyD TEER rics +m objects and chases Static Fields and Methods IBEX peers i wf ate sen ewe a Benes sen Meigen) eee ae tte pn tlc ten etn a ato Since fast dom see ea mito intn Spe Prete eee SO Sa ST mp noo (eee aatetemeen os 1 the employee identification number for atry: \d of ary so othe current value ofthe static ld ert and the value is particularly use for elds whoee types primitive or an mute iumutable if none ofits methods ever mutate ts cbjecs. For exam class is immutable) For mutable lasses, the fal modifier i likely 0 confuse the reader For example, inate fital Oe hiredte: merely means thatthe object reference stored inthe rite variable doesnt get changed after the object is constructed. That does not mean thatthe hiredte objects constant. [Any method i free to invoke the setive mutator on the objet to which hires eles. Static Fields and Methods Inall sample programe that you have seen the sia method is tagged with the stat modifier. We are now ready to disse the meaning ofthis modifier tat las Thats, you would need an cbject of the rath las to access and every Hi bjt would have its own copy off. “Another static constant that you have wsed many times is Sst. ot It's declared in the Syste cass as follows: pubic class syste, eld as static then there is only ne such ila per clas. In contrast, each its own copy of all instance fields. For example let's suppose we want sigue identification number to each employee. We add an instance fel the Egle class: ibe sta Fist ernStoean ot = psc SpOuTOW PUE SPIRES OBIS spoou west nares aolqoatg spaasun put 39 PO yeaonersagy 724 59200 Ae Reto en 38 UL SR A uo eae LP powyou ues (se payau syns es pox sade S86 aT JO SHAT HE PLP so year 20g 0k fe BUR ONS POMP IANS TA pow sake spoune LOPS AT pannus ©262 1S UN sues 21911 "Se REA Spy BHEIP aN SHO>E HED sPO-T yup om quem 244 ng HEU SED aes sagep om ing a ay spray susie ssan3e TUNED nok ‘SDelqo VO He pee sun Aani ap 398 0 UE ons Bf, SIONS OF REE Frower ap shemges ured. spo use MO AiwD 0 DoIgo ee AUR I useasdo und ayy “aqdexs ang spelgo wo rezado 08 9 aa cn om sep ang A, SPAT BE espns you pnous nos psos2yon ensnon Ashe a Bers uy bere eer 1010 acre ues spogaus agen ebencu Cuwureo eQu wos sysedo a 080 10K pots pe pe HES ION AO semrenarmis = S980 3 reuotouny eues SAE oy ro ue net A ase pu AANGO w F 2aHdeqD Ea Static Fields and Methods RES HE os osrancnes Y | TP: Every cass cantavearate mation Thats handy tala ostng ofcosren For ! youean adda mun matt ote tla clas year, int ent, nt ay) Gregerancaentartyear, mt = 1, 5 "you want teste Eaployee class insolation, you simpy execute ji aployee the employee cassis. apart ta arger application, then you start te applcaton wh Jan Wpliction ‘and themes method of he Eyleye clas is never excited. OEE —————E ‘The program in isting 43 cantains a simple version ofthe fale class with sate eld ext and staticmethod etexcd. We il an array with hee Eployee objects ane then print theemployeeinfermaton. Finally, we pint the next avaiable identical umber, fo dear ‘netrats theese method. "Note thatthe tps class aso has a state sin method for unt testing, Try runing both sx exp popu gus Agse9 we NOK SE mt Poesy ond © aBuey> cy POM £2234 eonpea jon ‘soquur) sd 98ST + czajpursed posi 0 SPR] OM anawnor SHEA org Bent ox wm sapere DEINE S SHAN. 9-¥ SIAL vaiiioaicnieiiat . von app yUeue> pomew at powjaur ag ag sues eu, ames Aa 9s fie (Bens say -PIO APIO axa podoyde Brag sacar [FORTIN cena con uy oS ou sx agesea youTesed ap Pu sPHO PONTE psa 3 MOUTEA Gon) oan gags es itp ayea at te pouTag UY "POM MSRP Ea ‘youre pow ‘Srey pue mDalGO mF JIdEID sumo une (p08 + a ga go ps, ao oc /) (2 917 EEE ON ‘popayejou are porn eqqro ging polar kpe send mpeg ee Soy _ pote vs yao ane au svensuowap umsfond pA spam ple on oe nng es on oN PE IMM R pod ego ey Ka PR oF OLIN FOIE RdAM HERR RAE papdn y som yay ureSoud ayy “s>eyosniy seyensuoWNp FF Sune] ur Tedord ay, “pelgo nou eo 1yauseawsered volgo ue ayeurioUED poweus Y ‘repurered polgo ue jo ays aig aBuewp ue> powpaw y+ ‘ene veqooqam saqumu's mp)adh annpemdye sured e Spur POSEY Sep puemeaO wy ai RN PORE sioiauresea popow orincconcin EEE ST Fay aang emma sesame Sri tia ag er eae ee aca orton Chapter 4 m Objects and Classes 0 “Tne retum ype i ot part ol he method signature. Tats, you cannot have two mathods rh hm sme names snd parameter ypes but cterent retin pos. _ hte annie ni orem ———_—_—_————$—— Tretwoon folie and loal ariates, You must always method. ut you dont eisaze a eld in alas 218 false, For example, consider the flees class. Suppose you don't specify how to nitialize some of the felis ina constructor. By default, the selary Bid would be iniilized with @ ‘he ae and hirediy fields Would be initialize with ml. Ld note a good idea. anyone called the gee or gt ebay ul reference that they probably don’t expect: Object Construction ‘Youhave seen how to write simple shat defi constructors that define the initia stato your amen ett rns porn a ler tea me "is for wring construios. Wego over these mechani in the sections tat low. Overloading exception FW 5 ut? Constructors constructor with no parameters. For ecample, heres default ou write a class with no constructors whatsocver, then a default constructor PrO- lt constructor sol al the instance fields fo their default values ‘ontained inthe instance fields would be all boris values would atiables would be st tom. supplies atleast one constructor but does not supply a default constructor iis al to coretract objects without construction parameters. For eample, our original oye clas in Eisting 4-2 provided a single constructor: the values used in the specific method call. A compile-time error occurs ete Canootmsteh heparan orifmore an cn hah prsibe hs pecea called overloading resolution.) fe ‘ “joa a Kyron yon suse on wap ars LSE HS pores og poy Kero ue (sono nln wi ue via a) 2 FD) Pa apn ug ey eaves Nd 3 Ubu FFD UESLON SO pnsyse «pp a ment t sume ‘ oe anges = Ges ‘pve = sa ees es ; ) lanes sgn ‘ae Gasnsdai ey 0 opnayse uy 285 sydureso we sraraH PIAA yoo Sap se Pek AG-SNG REMERE OEE A SHON HEIR TEL | _ypstin an pag eoucevson me mS TONG PPG VELA SA EEE tn ares amomesed wpe dts9 2g Ue NE NE AS PE , i6g se E _smoos Se 2zeR UES POX "PYLE SE Psafoxdi peo asaya sop loge 29puCD TO POURS Fim PETIA PY E Feet ordarxs ue sami anes vac Vago ne uep ons WOREETERN OH, ‘angen umes 24304 pay aoueynut syogaed v9 0} paou ssp jo szOHINUOD Te THI AE “romred st neyutssngy.=s}nos9 ]PNSUOD we al0}oG HO PUTED st WAU SE SH, 4 dames agape sjoneiés 68 tag + Be Seg aE sr, we yy apaered ypeo aid sxurureoud 0g me avo sss «paw van yey Tov 04 900 tH PEL ot paou ROL TNH PLANE A MINH : wioyaa SRD sajdwwexe 204-woanryop seep ap wT PPS Ae or anew ese Adu WED NOK, -pryBuqueus SupAaUOS OF x pray souesuy Asana yea so;nysucn a 3 smppre yep ans axe 03 Fapt Pood aye sa] aeneo sk Jo Spey SOuNTS, AA Jo ayes THRE AN 7350} shee Sse gnorago ue> ne ‘se eur spoupaus 20;7ARSUOD ap PEOLBAC WO HOK VENA, sous soyaurered S392] 9f8us 205 pdo woRDRIOHIUT PION TONAT "souspu zaywusese apn dn auzo> oy SuTERST eH aqua ung {ung 70708 aa LOK PR) OHA TAN KON NON ‘SOUDN Joyaumns0d t } omanssng ig ‘tne fray ve rks 8 30) ann ure ne Ket ‘re nok y eso }0 (Crated ou gn) ENASUED BNE epMONT STU MAK UNA wns mu nana ef sui ue apni huge 9 ney ofS NOK OSAMA HEA OK HI nok p opnaruce Bu e uaa gia ser nok ou no siprauCD eA ou ey FEY ‘rep nok vom fue 9ERSING YEON 01 #0 ARK A BIN Y dH OTEOKE NOLO ESE ee ‘Gove ago @ amid Aun "oon ob onoy sek oeTeAG ‘yu poou cua amar sprue wy ke a Meas eeds ER SHER ‘ 5119 "295 5 9 Hn oon ‘yao we wang ane pInOM secon euso asereeonts 25010 sv menssnoet FD] oto ps eg pun ey Se apeL one eet may ee AAW RION sre py -s0Gojdu yep ems oy eo eH SEP RIM CC (01 804 “Can ames gop a asd Ee rrr aaapmeno we i Object Construction IRI a Calling Another Constructor son oe ‘The keysrord ts refers tothe implicit parameter ofa method. Howes Trek pli ps a method. However, the keyword Lf the firs state ofa construcor has the form ), then the construct constructor calls another constructor ofthe same class Here i typical ecample: js initialized in the object intiaization biock, no matter ‘constact an object The inisalization block runs ist and TONE no lepaiosn fader rialzaon lod oven ugha aon defnealatrin he 1A) ons car nv comprare i eave mere (9 # AEST. rst oucre, oar cro 0 log “thse many aya inlining data ds, canbe quit consing 0 geal posse i ‘re contruction process. ere what happens in detail when acon ‘You have already seen two wayst initialize data flds + Bysetting a value in a constructor + By asiginga value in the declaration “There is actually a third nechanism in avait called aniston block . ai called an initialization block Class del rations can contain arbitrary blocks of code, These blacks are executod whaneveran 4 data fields ar nialized to their default nializes and initialization blace ae executed, inthe order in which they second conetractr, then the body ofthe sec> sone ey plas auesut ‘umm ) (Orr a8 aiqe Prrererererey e268 te “wpa of seston wee spoquoneAMN Ney. pera woneaene solgo ny JORKESUOOINEPY s (P80 yn sopanou rapowe ere ys Sopnnsuo papeoiong ¢ ‘uonaoe sna u poesTDsIp aM te samen aM 7 Aue ShoNs Buy ag werBoud a por wo -zaey ans uso pe as (a9 ms Be aU I pe LD oe Pel {ou tue sess sae on 8 mop Oma Nen pena ae | waa uonenne oes ea Dorers sep 04 ML ee ano cg onearek ces Spun un spa Ue mS } UH se 21g esr gum enc oo Ca ———— eet “uonerepap ssop ‘agit avo fara yong ut opu0 ax para ar sporq uoneerA z Fears Ppy IRE TY “nya JeNpOUE oF AMA Bs ANDRO Mok sop tm to sPRu ones sprey soueIsa OAT PapeO| IY st SSEP a URyM sMDSO LoHez Te 95521) pur SDOLGO wy sardeyD cai voioe SE seeds cleaning, Just as importantly if clas you use has such a method, you need 10 ‘ait when you are done with the obj FE ote 2 oversee in for using packages isto guarantee the uniqueness. ese two programmers come up with the bright "As Tong as both of them place their class into ges such 35 c.trstam. Oreja. From the point of view of the compiler, there i absolutely 10 le, the packages jvt.uit and. sits oom independent callecti Object Destruction and the finalize Method Some cbjectorented programming languages notably C++, have expt destructor srotnode for any dearup cou tat may be needed when an objects no longer used. “Tae ost common activity ine desrictoris redaiming the memory set aside for objects ‘Because java does automatic garbage collection, antal memory redlamation isnot eded and so Java doesnot support destructor, (Ofcourse, some objects ullize a resource other than memory, suchas le or a handle fb another cbject at ues sytem resources. In ths cave tis important thatthe esourse beredimed and ecyeled when tis no longer needed. ‘ou cana a fete method to any lass. The Fmlze method wil be called before the yestape collector sweepsaway the jet In protic, done ey on th ale mead for early any resources bat aein hort supply—you simply cannet know when this sethod will be called. package and all public asses from other packages. ‘Yu can access the public clases in another package in two ways, The fists simply to ‘dass name. For example: Svea ate tiny ~ jaa. Cte) ‘Tatiscbviousl tedious. The szipler, and more common, approach so use the Hort “atemmat The pointof the port statement is simply to give youa shorthand to refer tthe asesin the package Once you use ior, you no longer ave to give the clases thei fll ‘can import specifi dss or the whole package. You place apr statements at the of your source fle (pat below any play statements). For example, you can iaport package with the statement ‘You can also importa speci lass inside a package: ‘tert fa “The jel. syntaxis les teious Ithas no negative effect on code size, Hower i you Import claseosexplicly the reader of your code knows excly which classes you ust Ifa resource neds tobe closed as soon as you have finished using it, you need to lage it manually Supply a method such as due or close that you call to dean up w! “+40 u sonoaie | ussnpue anda om po soreue os ea Uy aBLINIS de EAP! PEL vemey eondanuse eh} r¥O uulawApoN Hered ef 6 Uo;eNAI SMOEO OAL “aug ew Au soe ag [Nn VED NOK mR (TET LA uote) + eee ay ye hE 2 "IBY ABE ry UE eu 8 ase © O00 ep, ELAN BOLE 18H, OIG ALD . “sononp apni og pH ULE NOK ART LOR Es ssp eS tg Une st oe Aan ROK" E yo sium gn pened om si or 101 dy wa oy. Br ‘St OPED PAO DS er bumeisca srx9ea 90 BI SN fae BEB TO} 0p LCD ++ 8 OOMEEE Saves (uj stoneeexp a epneU aN cen enw a 4 vow? FL Fe tage omy on ou mug HH OENIED hfe BUI +40 BION 49 — pean eer mod dian a (enopuy weetso\emesange) wees | ne a pte so mesa an Bee ng wy eee a on i salar aBoped mg og aE Semone “aeyped ymejep 207 UF pare>o] ava sasTEP afdinws pe mou dn suru Seped ov soy sSieped nea MAL eee PAP TT ces ng um oom nT HES AES ag aduroe soy aiepped on 5500: Mocdoy xg ve aBeped a 7M a no sour sospan ye EsU09 7 OT #N TK e Desra ‘ajdwena 20g hem forqou x04 uf SUORPUT xn ues nod Sve gran 20} og HIS BIEN NOAH: SORAMS [ORTUNBEN + suede soy ene ornesd oms ae asap a sap 9| sues ap HUTS AL am aa araiqge ox ues a ssuraresTond Aue YN ARAHOP Ses ‘ests Bo wetgeese nee apt lerencyn non s din xpd ypu vg se REI UAH S'S IS “ew sdopeg ods exbig snes Lxso Mu og noes Ue Na ‘ts th ‘suodwy ONDIS steped “Sasme[p pue salqO w Ide ka DEN crn cs nts 7 “The program in Listings 4-6 and 4-7 i distributed over two packages: the Pacagtest class belongs tothe default package and the Eeloye class belongs to the car.orstasn. beara package. Therefore, the flee. ara file must be contained ina subclaectory cnfest forejna. In other words the diretory structure isa fellows sta ‘The compiler automatically finds it operates om les (with fe separators and an extension preter loads a clase (with dot separators} TATION The compiler coos no check he Geto structure whan orp sue8| les. For example, stppese you havo a souoe fo that srs nh the dectve program wit un. The virtual machine worn te funy asses when you by 1 be progran calendar» nev reprise yer, cnth = 2, day); ge -ssSeped poyess seo 160 219 VL e=>npat uo no ror smndey i 95 TN 901 PAP aq UND SDSS sOHNYOU eyed Joos nay sexo aSeped snonoenond jo arst xp sauppe 01 fis oped ae teow imgourosn aeons eats woRPaINNE WAN Oy ELAR LOM SHEP UND “Serna 3O et, Gi aut eu erred asoyn sos Pou sae o Spey -stp Spndxe 03 sepeoy ssep op pa88y suoyaurardury af ap 'Z'L MORIN MBAR al ap emia pordns apoo anmos oi jo ed spn aSlped wen ap sep aqui KA oH aduTEXS UE ‘Srarey prosnkay amid ap 244 0119805 0 Koes ATM STEN S wo{AOKE ay, WOR Bgnsdenua oyeanq’aaineo jos aise aBepped Buraq on me ys day} JO HL 7 js soygensey so}oyp aveURNO;UR We Sea REED sp ‘SO|GETEA IO} 49 nopey qs we ey Soyo Bareren om PRIME oF amg Fp odered ynepp at—aSeped aus og ersomep sp Aun asa Sm aM Se poagep You sm ssep 080 MIL 9 ed wo 7-4 ATT wT west a OPSOD 2Soped aes a9 w spouse Aa peomooe 9q Ue (GPHEA 30/PONE ‘sop ag) ange an mes 20 gen Appa op nok wow eID Tea Se ap vo pon ne eum} aon Aq pe 949 se piles suneoy sed poo sip sab ap pasos APRA Ke POR e-pamii 209 ae Susie a 950 apeod sen Bay exp wvongy afeyoo! ver anno sez} x sd pute a6ey nO a sab Souhonuos mayen: Aopoapgne apioa 95S See Ap 29H a, eet sept | pyserepaag mo uns dung sfernd sev! a OM soup fais se ee se rb pRTEROE He ogo sn EE SGaoo iy tegen seed pn stgeea uP > PPE END ‘SRaaednd stn 0 oesou ono jo 80d eo} sap me Pp eS ake ‘sey Sonus potop ouaresaixped nee Ag spuadop a ean’ © AeA hepa wars » = (ofegu 8 ang aeand te Maes wns Cr pong oot mo nok —Agn 9g eoxd oy sure g zouREToad ay) oyrpou equ tp odie Adis pue Aammy e ut opooayp pak owe fn pacens 4 sient aygezea a ayeur oy ajeudoxdde dyaaqua u29g a8 0 sulbdizectories ofthe filesystem. The path io | rectory. Buf you have et the classpath and forgot inlod the" decoy. your ‘pesems wil comple what ova, btthoy wort, plies : yaaa 2 ‘The cas path lists all directories and archive files that are starting points for locating brary classes. Youwill seein RMS? sees. Lets consides our sample cass path: Poe asi: /howgse archives achive ja a machine sears forthe cas file ofthe cen. trstsn.cere na. Egle first look in the system class ile that are stored in archives inthe jeitband iat cecories It wor find the clas fe thee, so tums tothe cas path Teshen te ge the compiles fist needs to find out the package se. consults all aor directives as possible sources forthe class. source code refers to a cas apie. The compiles then tis to find uaa Ele (because the jaa. ag packages always imported by default, | Sn. Spey, com estan. coven glove, anc payee in the current package. It searches fr enh ofthese clases in all of the locations ofthe lass path. tis compile time ‘enor fmore than one dass is found. (Because classes must be unique, the order ofthe fier statements doesn’t matter) Epler cn easly locate source file for public lasses, However, you can impor n0n fcc fom the crrent package. These classes may be define in source es with d= Sent none you import a dass from the crset package the compiler sewches ll es of ie curent package to See Which one defines the ss. -zasonsop 29 Jo Sune sip iat asp no Aang aeneDoq cap S20 ae | Bapeon as Kom oj 38 ue 2PM “dius Buon 205, ciajumadiy, poredsouour 30} ap1/>-ap2> ‘sisoydn 303 pow RLF] ase we NOK “pe LO Sen y Ser hq pamomey say mu oy supe yuaur09 woFNAIIOD spur pu / wpm Sze uouro> Y oqNDENp Bye} a IGOR AH ‘sipumuuoo eg samgeny sean Jo yped 204 uoWTNeDw Ap (pynous Pre NOK, ‘gidetr5 ur seoepays '¢aaydeys ur poompom axe sumseay PADIONL J Eq “sqaunioD wopewaun0q, ‘uy kpreq e 20 yds pus w cru au puEURUED 84D} > eops pool e sa] ou aus © o3uo pads 9q sons pueuTuoD em U9 a Seppo my ada EN Documentation Comments Chapter 4 m Objects and Classes ‘Method Comments ‘Each method comment must immediately precede the method that it describes. In ada tion to the general-purpose fags, you can use the following tags: parma deszrprion “This tag alds an entry tothe “parameters” section of the current method. The description can span multiple lines and can use HTML tags. ll ran tags for one method must be kept together. + ereumdesenpin “This ag adds a “setums" section to the current method. The description can span multiple ines and can use HTML tags. + sears ls desertion ‘This tag adda note that this method may throw an exception. Exceptions are the topic of Chapter 1, Here ean example of a method comment foe Tacs the salary of an ployee arin Byfercent the percestage by which to ese che salary (2. 18+ 108) Field Comments ‘You only need to document public ldo generally that mears slat constants. For example: The following tags can be used in class documentation comments © auter name rust keep them all together. “This tag makes an “author” entry. You can have multiple tuttor tags, one for each thods anywhere in any of author special tag ofthe form version text “This tag makes a “version” entry. The tat can be any description ofthe curcent ture description follows the same rules a6 for the rhe ttowing acne welin al ncmetaon coments: oe . « place class, method, and variable comments directly into Arce AEcgmtcin i Tarcnytcstnenat l S tyinotejee sole Podclat fan near es : oon ws sitp0 2 uoqetaunoop eus0 94 oma om p ooU EI Rep ma ay Ave uci ey IEURE TAN Uo JK EN UB mun be vaeceunsop sop cr 2439 UDGEEUNESO a 0 eee Fe Ayn peat go vogeuounoop aur aN OF NOK Brady ecu sum seu psn pu sep wor pur era Rp mou) TALLH 04 psaazoo sony e2ano8 pos "von = sapuo Sumoyoy ap wt S265 Jo STEAD A scrub sme sf ml ayes yo Kee we apd 30528 10 98: bar myo mee pay ‘pant 3,80 ATUTETEO MOR -sonenappe [euoHeUN coy saSucup yon aden Ase Ue> 04 Son SL, "i " seep msm eur sppeg aoueisur Duo] “joj ag aves eyduree sng 3myp cx pe puyuapa ox 2989 sassep Im0K eH Brag ose soup ep sad 235 J sos pes opt 9x14 OF sss 9 sof 09 fe 1 see 00 0 soa-o8 on sqy TALLHL aun eM WOK atayn Keo;an ax fo ausEU Mp 4 KCNCEHF SPORT yous op woRenussaidar soup ur 986 $91 yp auey> ye par oxe foun axa mon une ny pene ngog rns ae nos nq Aigeuorse>00 Pot “Yow nox cuogemadenca saeyara ase Suqyasve Surop 3800 fo men oop wages paSeydayp 5 yumanoo gy ‘spp goo parsuueutpao ws aygeydonoe sou sassep sod tu oh aos pn saree spp ue oh ues 2 ‘SOAP 30 aatsueypatano oq oS MR syUTHL UBrso S981) Gh -x prous youre tepe g pomcooy + pur steps Panu ogy Waele Aen ‘pape 1 dg dpap, ea 9 wasn vO TYE APR odted TH HALA Uw Skdng *L SB5REID pure spalqO mp 191deyD Ea zn os [After all the users of your class are more interested in the public interface than the details of the private implementation, And they are more interested in meth ‘ods than in dats, However, there is no universal agreement on what isthe best style. The Sun cod style guide forthe Java programming language recommends listing fields first then methods, Whatever style you use, the mest important thing sto be consis responsibilities. “100 many’ is obviously in the eye ofthe beholder. thatare; simpler, seize the opportunity (On the other hand, don’t go. overboat ach with only ene method, usualy overkill) Her bad design “This class ra ments two separate concepts’ adeckof ards, withitsstutfle and drat methods, anda cad, with the methods to inspect the value and sult ofa cosine SE ae he names of your ses nd mtd fei rept. toxvabls stl have meaning names hat ref what hey open 20 et hes (Ite standard teary ceca contains some dubious amples Stchas hep cs tt decabes ine) od ceawenon's hata dss ame shouldbe oun (rd ora noun preceded Seetsjruve sey) ora gerd (ening word, Bei) Asioe FONVLIMAHNI re 4advyQ : HEE ies «tet Corso since interac, another fundamental com spc en coon MEE Ser uepiie besser bebe heer Se tn een chen goer oer eae epee, am I eed hcl as pein gee Se FF ae Roe hc Fe ee sae ethene ms the set of al manager sa suesato he sto alee. new field to store the horus, and a new method to sett ewleye Classes, Superciasses, and Subclasses Lets return tothe fplye class that we discussed in {ets ent elon tated in te ravi cope Supp) you have an tls object you canna apply the sttos method itis act among the methods that ere defined in the tpl class [However you'can use methods such a etn anc gery with tnae object. Even ‘explicitly defined inthe Mauger lass they are automat- ‘elationship i the halla Here is how you define a Miner However come of the superclass methods are not appropriate forthe irae subelnss In attcular, the getSalary method should return the sum of the base salary and the bonis. “Yeu need to supply a new method to override the superclass method! ee pos 2 sy Gee oy a > sum HOH ‘soug[es O47 oF PAPHE SMO pane in ag Spo 311800 10 pO UCD, PEE SPIBY PT UED SSePAAS ¥ MES TOA SY ‘son muoyne ys sxoSeseu ‘sg seo 203 pouiou Keys axe pauyepar Saar, _ssep seg 0205 sae og 30 wopton pano> ou 6 FSH aL Kp Jo PLPOUL HS ‘ eo.ay-asodmd snp 20 as prom ay repads og asm no Ssep ua p30 ‘solos ise a Jo poets A220 EDC ea mE BEPU 0; PDL AM yur wes oy Sipe ‘pour ama SED 16 ART OF ‘aovonbosuo a (usm oy Buy ae au poxpat a SPURY) POUR eS ooo ean ax aoe ose Sans ess cy eo A 3 SHI gOAE LL, “sop mode ao pougaur Ke 5st and ay ‘ae su wae ganda a—s0p pou rino Lass yey po ae Aa pay ead aso SR sue sporgat eed -spppyanend oo Sse ane SEP LL IO POI ‘rug ns pos eg a 29 sb Aso no va Pay fee ESI ASO ome sep sebum J pono nyegnsoxp yg sue sg) Segoe fo spf aud 2 0 src upon ys fey 0 PGP LASHER POM ATOM IAP DINO, yw 0 99 + a ‘spray sug pu ts a snfajdus a oy swoadde soups as ay cpowpau sm aH 2 MOH hoes a0 a1 souewsoqul ms 20¥deqD, a Fai ‘sasseppqns pue ‘sassepasodns ‘sasse|> Chapter § m Inheritance ‘Here's an example ofthis at work: we make a new manager and set the manage each print their base salary because they are aplyee objec ‘aRaiger object and its getsalary method adds the bonus to the base ‘actual type ofthe ebject to Which erefers, and method, ‘The fact that an object variable such as the varia is called polymorphism. Antomatically selecting the appropriate meth called dyuamisbnudng, We discuss both topics in more detail inti ‘Gre NOTE: In Java, you do noted to dedare a motes 2 i ‘laut tehavion yas do notwant a mete tobe wil you tag te fal keyword ator in Bos chaper) ee er eet Licking S-1 contains a program that shows how the salary computation differs for ples and dager objects 4 aestar weep EERE keeper eeze® beaease ssalge ssopiadns » acho wrefaud ap Joxauatpavalgnssepgns Pan uo no eg ‘emis yepunad yt don ures 85.3 8-31, op SueEAG| 0 Kem IDHROCY esos qed ous -tupo € wou Saspuspro sree Te taming) ue aay pyno> ag ssse jo ze 0 Buta sassepa “sasse)piedng ‘S05se 1) ec | eee ect soueoquy mr § “dey Classes, Superclasses, and Subclasses Chapter 5 m Inberitance Dynamic Binding or example, youcan alga subs chet oa supers ai ee youcan tig a ubcass ojo toa apercass variable cat ouniestand what happens when seo cal sapled tan cect fone ies ometed Carer cb rd wl progrananing language, objet variables re paioric. variable rage tsmabjeriofeenncrinmncetay sis mh ( son) called fin the superlasses of. ‘Now the coenpilee knows all possible candidates fr the method to be called. eters that are supplied inthe nd bes refer othe same object. However saf1] only an aloe object the compe is Bpleye and the setlons method iznota method ofthe 3 sperlas reference toa sublass variable. For example, employees ae managers this assigament were to sued Epos objact that isnot a anager, then it would later be ps sible to calls ) and a runtime error would oor, “CAUTION: av, arays of gubcasselrences can be converted to aay of super felons winouta cast For expla conser is aay of managers: is a aager, eaten an ployee. But mint agers ana sea areoter constructor then the compiler knows exactly ‘moifer explained inthe next section) This method tobe called depends on the actual ‘ype of the impli (yeamic binding must be used at runtimeruntime 1h our ‘nme, the compiler would generate an instruction to cal String with dynaroic and uses dynamic binding to calla method, then the virtual fers ofthe metHod that is appropriate forthe actual type of fers. Let’ say the actual type sD, subclass of(, Ifthe class “To make sure no such coruton can occur, al trays remember he clmont type Wt “nhc they nore uate, an they monitor at ony compat laren ae sored {hom For example the aay rete nix Ruger remembers tat tis an aay rranager,Aemzing sor an Eplye reference causes an hrayStoetaceptien, “ypreiory sp © osrueue (deat 29s Sepp 2 2 ‘wis 0 se 228 Boe orear spoadi ener ojorqe af i anos ay spor yoJoqumue axe sepeindniag seve sau spdarora 203 (1m Aonewo;ne are == ‘um esepgns ou uaKy'sA3 OP Ros LeU nok ooo wos eepgns 8 BuuD; Wos aoguos 1ua4atd OEM ROK ATBOSEAD Spoyjan Pup Sassoqp ung ‘soon oyuT Buruaaeed | a pow an nsUOD Rminsoip jdt m0 uy dqo04 a9 soe Adan amp FEN ott PATO Aone sponge © 2k OTT 90) spoNPoN TEMPE ow pu STIEASTS PHS |e Ssq ex ge posure ssep Yow 20 ayndkoconnd une yom xp 00FIOUL, ‘ae 5 poweure aun Ataa ores apm AaeD o)Sumusue9 sum 34 POM stan once ean 2 Ans ca naka syaoD Lay oI BL Po\oU SEATS 840] ‘soaseppqng pue Sossepaiedng S955") souejyoqer ms soideyD Ea HEE cares 5 trons Classes, Superclasses, and Subclasses keyword in the hope of avokd- lig the oveshosd of dyromic binding. Ifa method isnot overridden, and itis short then a Se ee ee ee ean a te ‘he vasiabe refer to and what tan do, For ecample, staf refers to an Employee [The compiler checks that you able f you assiga a subclass roforonce toa superclass ‘nd the compiler will simply let you doit. If you assign 3 superclass reference toa sub- ‘dass variable, you are promising more. Then you must use. castso that your promise ‘ane checked at rantimeruntime, ‘What happens if you try to caot down an inheritance chain and you are “lying” sbout [nstructions while processing the current one However if tie can be overridden in “another cass then the compiler cannot inline tbocauseithas no way ofknowing what the ‘overtiding code may do. ‘Fortunately, the justinetime compile in the virtual machine can do a beter job than a traditional compiler Itknows exaclly which lasses extend a given dass, and it can ‘check whether any cass actually overcides a given method, Fa method i short, fre ‘Query eae, and not acuslly overidden, the just-in-time compiler can inline the Thethod What happens ifthe virtual machine loads another subclas that overrides ant [lined raethed? Then the optinizer must undo the inlining, That's slow, butithappens ‘Soo to be reader Hint Uso a wrual base cass) Casting ‘Recall from Chapter that the proces of forcing a conversion from one type to ‘another is called casting. The Java programming language has a special notation for acoepie dene toe eee eee eee Tosum up: + Youcan cast only within an inheritance hierarchy. + Use frtncaf to check before cating from a superclass to asubelass. qs insures C ‘dae not gnerate an excapion xs a. snp retuns false. Thal mans sense, Becauea ul efor tno objet, Kucera does eer ean abject of ype enaper boss = lager) sata “There is only ene reason why you would want» make a cast—to use an object int full cxparity aftr its actual ype hasbeen temporarily forgotien, For exemple, in the uae lass the staff array had tobe ana lye objects because come ofits entries Actually, converting the typeof an objectby performing a cst snot usualy a good idea. In ‘ow example, you donot need to cast an tape object b aNange objec for most purposes. ‘The gseary method wil work corwetly on both obects ofboth classes. The dynamic bind- ing that cnakes polymorphism work locates the comect methed automatically. ‘Tre only reason to make the cast to use a method thats unique to managers, such as ‘els. If for some reason you find yourself wanting to cal setous on Eaploye objects, ‘skyourself whether this isan indication ofa design flaw inthe superclass. Itmay make sence to redesign the superclass and adda stions method. Remember, it takes only one ‘uncaught CasCastxetion to terminate your program. In géneral, itis best tominimize ‘he use of casts andthe istarcof operator. manager) ‘oensqe aun] ou sssepoqns ay) LeU Spoutau Te BUYIP UED nos IO, se pensqe se ssepqns ap Sey su nof woe ouyepan spoyreu: PEREAE a, soata0s anea| usa n9R sReNpOM aneynoA'SseP ENSAS we PUNE NO WoHA so sansa payuoua| du axe yew ePorROW 25 repo -soureu ancy soofoyun pre swuapnss og “surew a4 Se ypns tuossnd Aros 20525005 aqeus yy soynqeae eos are aay juoRPeRaRE 7 Ne] eH OF WALA ZO SUM, sseeerogns my pee wing 20) wesBerp somFIONET cam seeped oo (ou 0 pensae : “ossep asaip wooing sdnysuoneas suEuayul ap SOW Z-samg wHPNS & purwouny sense apap 1 Aypuesony sep m0 pupa SA] ‘a0 pu 008 upd est anf ry gpuerony seep A065 ano Jo MORAY We “om oj gator nod sanueyeut ayPode Up SP # SP LE Sse stun nok up [e19039 or Sauosaa Sep OYE ap "yO ates ty eNSGE AIOE ro pure eu au auooaq sossea Aupresary uRNBYUT AG dn BAour nod Sy -dupsop jug euuinyeso 1 asodsnd asoyn wordursiab “Aypreray URINE 3 AE sayin ® 01 ponnaur amas xp ano so}ey Sn sy ssepuEdns uouNEED eBuENpORT PEE “seu 2519 puneedo eel ES] es aur omy yom yra‘9 6 hep PO eq ou LOH EAE BEE eM IRON +40 PESEEEEEEEEE ‘sour ioyuy mS -2NEYD ca “assepaqng pue Sasseppanding ‘Sas5e)) Ea Chapter $m Inheritance Foreample, we will define a steer class that extends the abstract er class and implements the eescrigtin method. Because none ofthe methods ofthe Ser lass ‘re abstracy, it does not need tobe decazed aban abstract clas. ‘A.dass can even be declared as sitract even though ithas no abskiaet methods, Here psa variable ofthe abstract type Frson that refers to an instance ofthe norabstract subelass Suse. one pure virtual uncon. Inv, eros no spec keyword donete att lasses. Letus define a concrete subclass Stadt that extends the abstract Peri class lass Student extends esse “The Stuer class defines the gtescripton method. Therefore all methods in the Stat clas are concrete, and the assis no longer an abstract dass. ‘Classes, Superclasses, and Subclasses “Thepprogram shown in Listing 5-2 defines the abstract superclass Persea and two concrete subclasses, ployee and Sten. We il an array of eran references with Isnt this call an undefined method? Keep in mind thatthe variable pnever refers to ers object becauseitisimpostibie to constructan abject ofthe abetractPerien clas. The toan object ofa concrete subclass such as ployee or Sider, For besripton method is defined. the abstract method altogether Abstract methods are an important conceptin the ava programming language. You will ‘ecounter them most commonly inside interfaces. For more information about inter faces, tur to Chapter 6 ‘uowersdsous ep ny, susasvsiond 09 998 Sugondn -oxd igo A psn st sep nok cnoddns woyNe> Yl SP PDA I eNDeN “spy papaved ag o os00 unc nf sees HO) PUR parojnd ay ange tu nok ie opens PETES SNL, SAGO ek45 No Yue spelge nen Pp estan 9PSUPIPIE UE SpORHAY TEP EEG ADAG ud xp ssovegouea seepqne 8 eaeempane 13 30m cops eng 1aydeup snp fo SUL, ‘age pres om sy “oesep 90 o} ape 9q2,uOM ae s4 PAREPOP sAMIED] Lay Dy se ‘pale enon se sponganr pe ana} se pase 39a Se €ULSPU "MOL NOK Sy sson0y porosnoay ep “1 ane = sof tag ead > (fey 0, "yu uy “sek a “5 wep 8 Gnsnold anfen + , oy Sopofee apn Owntines eng spon Hold, HAAR RECS USE SESE Sead Eds aS aesedsEE ‘au Buns ae aeane ee) = [EL Ses pnts ne aeons od > otic tecomicspecten EEE Protected methods make moce sense. A class may declare a method as protected itis tsicky to use. This indicates thatthe subelases (which, presumably. know thelr ances- method in the thet das tests whether one object is considered equal to another. tore wel) can be tasted to use the method comely, but other classes canoe. method, as implemented in the thet class, determines whether two object fer ‘good example ofthis ind of method is the cle method ofthe jc laso—see Chap lenical. This a prety resonable default_ftwo objets are identical, they fer 6 formore details ‘Soul certainly be equal. For quite a ew clases nothing abe required, For example. it tutes tle sont locompate to sas cj for aly. However youll cen [qd SuNOTe As tppacn, ponadtentins hiaw ae dove Wal anno ato in which tao objets are considered appens, protected features in Java are vibe to all subclasses as wellas tn peas aoe iad Ga Ib same pactage Thisis igh difeent ror the Gr meaning ot whe they beve theses al ts the ten of preteen dam ew is ste an Gre conser two employees equal if they hive the same name, salary, ‘ctualemployee database it would be more sensible to compare this eampe to demonstrate the mechanics of implementing the Fersisa summary ofthe four cos modifiers in Java taco vi. 1. Vible tote dasoniy Gre) 2 Visbleto the world ai) 3. Violet the paclage and al subclasses (rete 4. Mise tothe package—the(ufortinite) defult No moderate aadad Object: The Cosmic Superclass asa generic holder for arbitrary values you need to have some knovledge about the ii Sr cha en values) are not ejects Tess method reams the asf an objector dics th etd in etal ter ainda gate ome Ss tpi non r ajercan oly be opal when hy bel he bane ase ‘When you define the te method fora abel rst cal eats on he supers. that, ‘ltr yasy then the ajes canbe eal the opens ede ae ga then ou : ‘seat tcompae te inctane iso te subelss. —$<$<$ Gr NOTE: Gre, ters noun ot cansHowarar fay pear peo cc Beers ee eH ee -ponrouoydiny ut 0 ‘28 one ue axed 1 2fge a4 02 ue Aas NOR SUDLE ‘sswnaanpo ots YPHEW SPIT: sosapensd 30} = 267 -Afenba yo woo I paras o1360 sway. “tate uM PLE e sumsar 9 249 35) jmp ue ose seo sppyan aredwo 0) wag 2 any 09 ade pays Jo pO 29140 8H wT nut 31 9st uouraoo ep enp gpesd uy womeztumd ue nfs aweUNe Sn], sana uatss (205) ‘alquane of eDRURPL 24 4 Buopq snjautsed ayy ung seouantnae: : conpage ep eu) uaa we Sue30| yA ayqmpea iyo oy 56 or pau NOS Sealy BALE AES HAHN, odo} sop AsBsg UEM 9 UPINO e690 adept Bure seb hues jssusu Bsn yseLNL oo SUDAN Go| Sto suet Ke BRE NEP 3 _aae_—seEA—aeeE esi k pue sun summit porradar won paSinyo _arepap pros ax pu 0 eau] mp 25m pod 28 LAL _soqou dfn so pou si, Sus Aafenbo 105 qT sadorda we pss ug pan an ‘soyasoy, zap 290} wap yea an ‘Sasetog asa ya ag “=vEp aay pe Le jes sure gues ayy api spalgo fen oon ant 208 FSPTay Bumper ancy Kay uN enbo 2g or s901go ang sapisuon an ‘saSeueur pu sosogdure ayy yo de a gous of nbo ago} esepgns mareyEp go s>alg0 MOE DUE ih 4s josey 0 aon use nod wala ‘ssepaadns yp ih yo uo9O Kamnng epee (peu uop S255 7 Suxpooord axa up fss24onu0> 08 0 nsumamber Saounaks og vay aqenbo 0 unos opens punsp om ase asany 1308 28 KO HL, eno op soy unt U3} pou oe pmngja aoure sua, on SSEPANS ESOT STUL ‘Laon 3s o sonuees xp supa pmnoys Kpoqou: 1 8S -oeityy azepop 0} 6uos ayes pyro a ‘porTenads yess odie Je AR HOH2HOH, ssepsedng 3809 941 P9I9O suena mS dey Chapter 5m Inheritance Fy] Terifyouhav tekst ary ype, ou can eee ni rape tie hak Y] tet coreponding ara laments ar equal istgke when enplemerting the els metned. Can you spat ovicsneconicspeces RRM ‘rable -1. Hash Codes Resulting from the hse Function eaing “The tsiade method is defined in the hject las. Therefore, every abject has a default fromthe object’s memory address. Consider this Nota the strng sant havethe same hash code becuse for strng the hash Cotes are derived fom tr confents. The string bude band have ferent hash ‘ode ease no use method hasbeen defined forthe SrimBité hsend the ‘kt incate method in the ec Cas eves the Rah code fom the objets mex ory des ‘you redefine the eqeils method, you will also need to redefine the hashCode method for tat ours igh eink able (We ss hash bles in Chap? ofVole It) Tetahte method should stu an neg (which canbe negative) fst combine the ‘hash codes of the instance fields so that the hash codes for different objects are likely to Se idly catered For example, here is a hashCode method for the faployee class: as Eg ss oe pati we aoe so2peo ysey atp pure surest Sum Summsos oi mn on enn dex eye Quis home 9g xo eee SN ow De cooumove yndte em + om es nL UM DPE saydavexo 20g 73019008 ap sen fesqeesoinesyrdu! -yerdeo 8 palgo We Zenon 008 ago ap jo vonencauag dur eo as0p spyoeaq asenbe agponoy sep a9 jo aurea ea; snp MONTES Spo ssn ayn Sugns sworn se aay 2a pono fang ayy duro pede apy olgo sn O-nfen a SuTCS sar os w summary pout Gaga a9 5 ep pougaus Neo ROY ouron 691.150 3ur, “supoo ysey peop uaryar 0 peau aah 0 aod ‘fq Are 2g ue> apn yey "pslGe op 3059 “uous feu ogo sepoo yee ou 0 pesoduca 5 yun op UseY w and uno cy powss opt sesey ns 3 LED aKa Kee 0 Sp ONE OK ne 380 aL ALGO commer as dei FE ee ss icine 1 Genotos an ary of itepers) The remedy ete mato tea. Tne cose The wri method ia gret tcl for logging, Mat clases in the standard lass libeary define the toString method so that you can get useful information about the state of an icularly use in iy racommend at you aad «toString mated 0 each other programmers uno ute your classes, willbe gate “The program in Listing 5-3 implements Erploee ancl niger clases, paepepeseserersee oleae tee soso waz ap 3) paso Kuss a doo ue 28 np oy Arcane oo uot aera ea a 949 4 JO BHO 8 SHED ‘ome D6 -srsep uno snow pout ny span prone nog. oso ayo one ap suseanday ey UN = SUE (REG Hs — uno snok 7 pogau sap apusai0 pyroyp no}, SUSY! Fy Pe IOOENT FO jae co ony ed soso oy jet surges peo 25 oqo om saree Toning ost co, paopisdeoun ig soseep 20j uonezuacondas sum caret aos nod sy aoeigo xq snoge woneuap S\eRUOD Tee AA ee = nay} cfeoan, + Aares + foes, ae + a, + (2m pense lama + e+ OOM {meee emnuin + + ORHSE et i asoie nibpoeeregan ta Copennoy ae nt sp aes ap Ga Ea ‘ssepuading 210809 241 PIG mmr soo add new element to an array list.For example, here is how iA] Nore Senna tengo baa tots ae ‘wth polenta peels forthe unwary. Wo wil hae alters to ay about the clan et Ghapies, ferences, Eventually that array will jie If you call and the inier- the + Chass getSuperclass() eee ‘eh peas ofthis das 5 asc Gonerte Array Lists mary programing langsages—in parc in C~you have fete sizes ausys teompile ine Pograssnes te tenure in ean siete How manyenployes wilt insdeprment Surly notane then 0) ‘What theres = harongous deparanct wih 1D employers Do we want oases) nts for every deparinent wth st 1 employes? ay oF 100 object. Then, the fst 100 calls to add do nok the problem of dynamical mot youcawot cunge tea ines th common station's se soa simlato ana bt anata eve cements witht your een owt te isa gris witha pe rane: Tospcty te tpecfte ra lot hele ou oppechs sate cose nang re roe You wl sarin Cop how ode your om eter ew kn ny of oe ets to wee on ea returns the actual numberof elements in the aay list For example, sat umber of element in the staff array list. Thisis the equivalent of jing new elements will move the block again, is when you are sure you won't add any | ao dese ana un Aaedeo ap spassx9 vont a aye: Haq oo 20 wo yet 0 de poy au ana spouts port en 19 9up aBuEYp 20 ss9008 oF xepus [] qUESeOId aon ope ‘eum yxg Scoanuoo yimon8 agewoyne ay) 22350} 3409 BunpOU Afpreomop ‘Stuswora 1517 finssy Busssoo0y ‘es aus 0 35 Kotse ayy Jo Aapede a ApedeoaBesoys pasop an eaze 8e1038 ey suawape so saquimur a8 ap sores Apede> > Chapedeo sy See ag ue 28 ss ‘28ma>0) a9] Sexe ut paryeduotina Guuote saquntrouh Propeaq a uous. fy in sunnassCeaty 959 Aste po pus oy aU espa (Ge Da ermeny 0 peu 16 0 seo Yuerbosueg “fap ue wares ong peussep vain [9] nc 0 pote a8 ot pu sasse9 ORB Ov as Sy OS 36 MAT FS ALON J Kens ojo Aapede sams jem Et -asn "qusuipjo yoy Lense ue 328 0, ‘sf Aeaay 99K souesoqu mS sodegD Ka Chapter 5 m Inheritance getty) 3 riedaet ? Se yar, i anh, ex Geriatr year, snth = 3, ‘he berate class, aac soe Fal 7 uo, a ye wetesUoD BDU! 99 Pron SudCEICITe eA HUNT HOHU MC Suc LA] Sao pag wR, 24 anu) ponomas.ag 0) yuDuna> 2x9 jo wonIsod agt wap pasowar ay. 71 3A0qe SHRED TE UMOP Sys PLR: owae mau, (om pur gaomoqaqisn) von uomass 2 apg taza “yous we osu oy ueuye da sys (ie 1 pa pee (- oms mg usangag aq yn 38.0 yosun 319 0 2=pU sap poypods ee ‘sian ean se8 6 Lo sopamoun ip (¢- (ais puepuaemaq aq isnin) vowed oma, Saou snouad ip Sugeno “open poyrods ayy 16 paola» p25 catoyen st hey las es # Sse nox ways A=I2660.) Ea ‘Bupoqoiny pue sraddes 32190 Chapter 5m Inheritance ‘The compiler automaticaly insets instructions to unbox the object increment the resulting value, and box itback. chooses, wrap commonly occurring values might succned. This ambiguity isnot ‘method when comparing wrapper Finally, et us emphasize that boxing and unboxing i rourtesy of the Virtual machine, The compiler inserts the necessary calls when It gene codes ofa elas. The vital machine simply execules those by codes, You will often see the number wrappers for another reason, The designers the wrappers a convenient place to put certain basie methods, like the ones clase wae a good place to ‘The APTnotes show some ofthe more important methods ofthe Instr lass, The umber classes implement coresponding methods. Object Wrappers and Autoboxing contained inthe string 5. The ating must the first method) or in the base given by the ing must Integer in base 10 (forthe frst method) ‘tin the base given by the fx parameter (forthe second method). pry { ooneuaieg sydinexo ues 044 pejeroumu ayp uagse poxoaus Ay axe ssaonasH0> ap ‘Ssosse[g Wopezoumug woyounpame 01 (S08 PE) age ae sans odo a, TE = HE ang on uoRouny on Te Adis tase, Gs ‘sontea 30309 mg vornary + =ydumso yd oso cal onate woo eyed oj o08, pe porous je, “rojusezed yup 01 uoRyppe ws) slqo 30 zoquamu Arengaze ue aapooarue> porgou axp we saousp I] 9pO> eae ou wed es 1 sie aupaenay se se\p0.49 pue sajouresed ony sg yo suum ages ey 2 0 sojauresed o oqun pony © pey powjou ene Aase ea Uae MO} stoqourereg Jo JaqUMN 9]qeHTEA @ IITA SPONTA, Soest uonerowneg sueiuayel ws HideyD El Chapter 5m Inheritance Reflection EI lace one or more statements that might throw checked exceptions inside a try lock “Then provide the handler code in the catchclause. ctor in the ua. larg. reflect package des and protected svember mermbers of supercastes Using $-6 shows you how to print outall information ass. The program 8) constructs a new instance ofthe constructor’s deelarifg clas, Persmatrs: 365 cars supplied to the constructor Sea the ‘on reflection for more infermation on ho spi RORRARZNRAM KARR CCHS SUNG EERE MORAN ES eEsaCSS ESTERS ER sanewoine syes9538 zaps enol _ag ven seep 90s a9 aps 90d 01 sadeyp pou ou uesond ena 36m ay "Por -apodSeo weddond ayy age agetene a2 yMy SosSeP ayy nou peD| veD sada "ean ag ey seep Ave zur ues! yey st ureoud sp noge qe TUNA SM sunwoya mS saidey ad |: tetein lace one or more statements that might Uwow checked exceptions inside a ty block, ‘Then provide the handler code in the catchclause. ie chject andthe stack trace othe standard errr stream, Using Reflection to Analyze the Capabilities of Classes the Cats clase retum arrays consisting of al fields, methods, and con- declared in the lass. This includes private and protected members, betnot members of superciasses Listing 5-6 shows you hav to printout all information about a clas. The program Prompts you for the name of s clas and then writes out the signatures of sl methods nd constructors as well as [ari ne ee > bi tcl ‘Staunton’ deca cls FPromion 6 thepunetasopyd the const See Seton fect free formations hw Sop pence sting ee s uy ses ap for pen wo ae SSEL> PD: /7 (star (iayagen pi “Bqeoewoyne soesous8 sapdwseo ene ep seep sou og opi yood of dep pou Mg wT resZoxd en 36n ayy ‘PONE so) feu nerSoxd ap way aygeenP asaMc eH Sse ap SN You "per we ILIA ‘ene a 84) seep ue zeAjeue ueD 1p sf wexBoxd s@ moge2ige Saeeeeeandadaronsecvassesone Pere e rere errr rere BEE vonoyen searow as ede Chapter 5 m Inheritance Aeflectionest. java (contimied) this cat. The metoderetumn an aay of lng the Cas object presents a primitive or ary type til objets gests ble methods ae ls ise -netbods gees resus al meth fh cass © [ar ination. ceflece Field 4.4 [otc etd 13 [lee iat represent the types of the exceptions thrown the modifiers ofthis constructor, method, or er class to analyze the return vale name ofthe constructor, method, or field in astractor and Neti classes) objects that represent the types of the parameters, ects classes) "eu be! ht ep the en ype [ef nets rec ier 11 "unsastng wih he modfershatcoreapnd obits tin lies. ose 9 02 ma HanytessoorRs's agdumra og polqa ar I {NOR EURANEX® Ty: anogyoe O} poxaU! fay HY, ‘um adie ye unowsou arane FH oT NOK sy woRsoYea3MG wwealoud® aye nos wayee WHORE aze ad PUE espa ‘EU 280444 20g UE Jo pt ouads Jo sU=IU09 aX 40D} ob AFE 11250095, “peu EIep any Jo sz; Mp Ye oO Ayenaze pu aA dy : spolge hue 0 spas ep ao sy pur sou ox ano pay ue> 1m Moy es 2m 296 Hepa aN ‘ounrumy 70 syD9fa0 a2fijouy 03 wo}ooLfonr BUSA saa sauang og plgo 9 305 fa ponents pes | pxgeur oun spot poy spuodsox 195°5 TRO OU, 198 ED NOK YEU SaNpEA ay J9S OBfe TED MOK “2802 5) \pagéases sp wr'ssep raddeun send -vorpos su use poxpau fa uaa way X36 4 SuITUEYGOW! sepUNS pur We ‘mid ‘s0ingyp acy popracid amen sayy Sse oO NASI PLE RM WHE osepindns uounnoo ai Sep zolgp assy sp Jo porpoure s poxouT |g ML | cc re amuinyoynl mS saideHD Ka Chapter 5m Inheritance ‘The complete code in Listing 5-7 needs to address a couple afcomploxities. Cycles of references could cause an infinite recursion, Therefore, the doyecialyer Keeps track of bjs ered vit. Als lope nie aays youneea diferent approach You'll eam about the details in the next section ‘oxen ue is ir mean peck ay objet. or ample thecal aa (jectanalyzerTest.java (continued) ‘You can use this gene classes, ike this: ‘This sa hassle-free method for supplying ‘your own programs. ig method that you may find wsefiis cojecatyer atch (Exption 8) ‘heue 29 20) se 20) Avo pausop 511) ‘xomnungey ayes mst fe sao 9 8 208 algo sero a9 8 3040] sm emp Sue de wna D RAge ay (ep p0lgo aig paleo ‘Kee mats otgjo.adG yrouodino: euyavg yo paras pins ones ay ‘Kea mouraipyoadyusuodkseo pu powyaur sn oy srjausered se 1y3ua PaREDp yy a Silas ys 20}, A ‘nan Kee ayy paves 2% 26002941 ‘hour o 244424, exe Sugynsar ayy Sunon Ktenioe way tego vst 24 walgpiaisseny asa Gael [ia] T= sQeratgprsitewy r= pI calgon ew aM “eae fg pxgot um yt pe ai Sauna aod uy 2a dojo eu an ok sending ead fide anor eam syoyue pims sp Sasoned a eae Suen we puedo Se not de ony pos Kt nse) se ww tsnovulp ea Som oy mot ence Sepped opt ta p00 inary o1u2p 274M 09 uoqroeyfou 8 soueinaquy mS ERD rin ES ‘Why i gelargth a method of ray but gtCaonetTpe a method of Class? We don't know the distribution ofthe reflection methods seems abit ad hocat times. Heres the onde: sane bjt emerayrosthjuct a) jf weit t AttayGrotet. jaa (one 5 ype, wader): a ' : Note thats ya method can be sed ogow aay fay ype, not estas = tebe : Tomie declared tobe of type sje mata ect). The inter acray type iet!] canbe converted to an bie but oF ebjers! Listing 5-8 shows both aray grow methods inaction, Note thatthe cast of the ret Value oftatraérn will throw an exception. _—_—_—_ NOTE: Wie present ths program to tutate how to work wih aays tyoughvohocton You ust want to gow an aay. ua fh ep metiod nthe eray ies ml 7 ray foes rot tan aay beseeeboreee forming ary. Static wi arraytinedbjec 2) yur ap 20 area's a 200 pany ywato og ut paddles sok sae pougeUrayOUL Le Sey Sep pe ap yt 154 30 pout _ap yale eg we o Page ads] UP MOA yyy jeDNN YaoM ye ISRO poxpous oes of, (srjamerd ou sam aiog 98) MT fon PON IONS on ep Adds oy 30 Kaze se opr spalgo set a eyed oy pet OK ef a059) int yo shea stayed porpaul aay pos Sutorey ap ‘Seep oye yy Jo porgoUs ae a SN ye 0931798 Ue> nok—parouBtssoyouesed ny ax “pout 2 (shar “3 gp aofqy aon D200) oe comer Chapter 5m Inheritance ‘The code for printing tables, of course, independent ofthe actual function tha is ‘Thatis the method of thetith clas that has the name stand single parameter of type eit Listing 5-9 shows the complete code ofthe generic abulator and a couple of test runs EI hetiotrsieertest jaa ra Taig. Sf to Sake ets thigh reflection. aa. doses) SeeNeoeneresasesee BOeREFEPERREARESEPENRK ERED s ‘Asthis example shows clay, you can do anything with Mth objets hat you can do ‘wih anton pointers in € (or delegates in CP) Just asia G this syle of programming ‘usualy quite inconvenient and always exor prone. What happens if you invoke a ‘method withthe wrong parameters? The isle method throws an exception. ‘Aso the parameters and retu values of ineke are necessarily of type bec. That "ean you must cast beck and forth alot, Asa result, the compilers deprived ofthe ‘hance to check your code. Therefore, errors surface only during testing, when they are ‘ore tedious to Bind and Bx. Moreover, code that uses reflechon to get at method point- ‘sis sgnfiartly slower than code that simply calls methods directly. Focthateason we suggest thai you use Neti objects in your own programs only when -olutlysecenny Using interaces and ne cases (he subjecof oe est hap) ‘almost always better ides. n parcular, we echo the developers of Java and suggest et using thd cbc for callback unetons, Using interfaces forthe aback e the nextchapteras wll) leads to code that runs faster ands alot more maintainable. suo oy ase su fy sion Seen pl no dj oowe Ge oy, csoansaay obey uy oeadondde ou Spenan seq Superson awa Sines Houoioquesanggede> ety auteur yeapaous Poe sPoy Sasoap een Sa aad yon ok 3 ENO RO ef eg sna adam ssn. apo my puny et sav pa sues Ss aba 20 spoons niousod BS 90) rapier wsryouied u aso sven wreda ome 2 ney 0 > fas ur 0 ad og soe 0 sepa UME np papal oa non ma en =e “ust (cot uy 29 30990 uy as nossa abode 9 separ spo apm gn Son aug anton swim oop no ys se ey esa unNSek Tyme dog epned susp ss st oy wast 30 ep ve mango ungouop ose Per array eto 0 fs a asus hparn agsp n Oas rma da a > soxnteg ate igeustnun ou ps NOK Popa apse ve M7 veeppe a mday S nq els oud ooo woe ren a yn Ne aD “uncr seg ysedndde no ar _sSepoou cut Sep we pe PLY 7 aL ERO SpE axp yon suonede PE 2 2pm ony ou SKMPHOIO HSA TAH aon ve ooo o> si evoust apes y ase e-, se usuonee soso rope SUL a 9c so Sate do pin nok ur no uae yo pu ou nok oo -pe einer eny alo sopesto yore mow ote Peg sew ute we pe oxen ssepqns # w0j 0} wogendinay aps aan, Dees w oS. now Sut ase Aes 30% op fotp pure nov =tp Aa pred are foxy ‘peop soHtyss 2Aey}Ou OP sq. ang ‘sep amy pure souteu aney suossenu07 see Jere) poou am seodns ‘ayduree 30g esrsoa0 ajdood soumowos pu sanes-apoo Apidae s aoue a ‘dau .o-, 29 pou of sue 7) odes ‘poo8 est porous s0|9 a sasepaqne mt pauepar ag pynoys pac asm jae 90) _p999%9 "8 “suosear On 20j ‘oR apond Yon ani, UsSop LUSK 2p toxonoyy ey pose hoxpsrappoy omg ss20e Ue sess ef 05,2509 Us, ‘Fone se spjg soumeu sou auyop oF wopr Pood e tar funy szouEAdend autos “pe pommad 2m 1200 “2 19 ems PUR fd Spurr Smeondos onipsoqper sep emsagony ows poy sue ayp and aM. Ae SSR, ‘soppndns ay spf pun sexe outucn 204g sone aps ui jen pong ane am sn sy aie ZieND en PuD Ores on somes HoMUT 105 SUH UBISo dees ag snus sonjea wana: daannumg sreddean Sin 6q sons si sapgumad se stowed ond ‘Reo sed “spoyjus a 30y AIRE PENA om EW Ones og BUNA Puesiojauezed von 90 3 ee ‘SoUEHaU 40} SIUHH UIs spar oyu ms sade Pe Chaptor 5m Inheritance ‘You have now seen how Java supports the fundamentals of objecterented program ring; classes, inheritance, and polymorphism. In the next chapter, we will ache wo r ha ter Zcivanced ops that are very important for using Java effectively nefaces an rer INTERFACES AND INNER CLASSES ai -spepsau a_gesnaan aig quawo,dun exp s255eP OH BO oy sosuoud se onan on soe we us STEP © BP OL sepa Spout 35 won A “sop wan ap aay of spun exp amok ye ze “Supra siy wo wonses ean ds ayes We MOK sO [2821 251 dxod y sneyant ney 03 apo» Bar400) ‘sassep Buneodoo> nanoazs 2X 40 SPIE ‘540 ue SoU BAe S9H}2IU! 90g ‘POUL a sequmuroagisod e pur enbo are foug 9 oxez X ueuy 29S 5 joo, eaef nox ayeydusoo oY ur JaSeULO} paow HA NOK “YEU IHOEARO 99] ON ‘posh Apuowuo> az ei senda, paouEape fesanos nod smoys amedewp SM, eo oes you ete yp NAM UH unseen poms onsen ue HOCH go> Tae am pur ROR MD HD rd oe. actualy has cprefo method, [Fis an array of Caw: the method is assured because every clase that imple supply the method, 128} oes not belong to a clas hatimgloment th Gpiribe ines, ten the vital machine tows an exception, BORE SEPA UMS YE BREE EE ey pote> oejayu we pey no asodlns“apduera 0g woe si (oe fagoyaztan 205 > “suman sq apse pu ‘nbo are fa ox3z soy sr polgn smn jroer anneBou e sus pur sen Pole Tosse sou pu saepaTET m9 IRD Chapter 6 m Interfaces and Inner Classes Although you cannot put instance fel or sate methods in an interface, you can sup- ply constants in them. For example: programmers do tha, her ou of hab or greater cart. However, ro Java Largs Speciation recommends thatthe rodundert kya tbe supa, and ws low at recommendation ‘Some interfaces define just constants and no methods. For example, the standard Library contains an interface SvigCnstnts thst defines constants NOT, SOT, MERTON, and so on. Any class that chooces to implement the Svngeastits interface automat ‘ally inherits these constants. Its mathods can simply refer to sather than the mote ‘cumbersome Siesta RTH. However, this use of interfaces soeme rather degenet- ate, and we do not recommend it While each cis can have only one superclass, classes can implement multiple interfaces. “This gives you the maximum amount of flexibility in defining a clas’s behavior. For eample, ass tplye ples Clowabe,Cegarable Use commas to separate the intorfaes that describe the characteretics that you want tosupply. Interfaces and Abstract Classes about abstract classes in Chapter 5, you may wonder why the programming language bothered with introducing the concept o simply be an abstract cass Object Cloning ‘There unfortunatly, mor problem with using an abstract base clas fo expres a generic property. A class can only extenda single clas. Suppose that the plone cles already extends a different class, say Persn. Then it cat extend a second clase, ployee exes Pesan, Comparable // RR Other programening languages, ‘superclass: This feature is called ‘support multiple inheritance, bec C+) or less ecient (asin Ee), Instead, interfaces afford most ofthe benefits of multiple inheritance while avoid complexities and inefficiencies Ha or low acass to have more than one heritance. The designers of Java chose ot to kes the language ether very complex asin Object Cloning Wter you make a copy ofa variable the original andthe copy are references to the ‘Sine objet. Gee Figure 6-1) This meunsa change to either variable als affects the ew object that begins is life being identical to oiiel but time, then you use the clone method. eld i just fine Feld gives you anot lize that phenomenon, let's consider the Egle class that was intzoduced in ‘Caples 4. igure 6-2 shows what happene when you we te cle mito oe ect Jos aduex0 ow Yo se saAKOGNE AD tae aopar nus nok poe tgs ae songaqetanamoy Spun a) ‘doo momen £0 24 no apis paouazaas ase yxy so9Igo BUOP 3,520 T— MOTTA, svonerado Sutuoy ajay aio ue> nol sy "Palgo leée Ue YRS BuO ON SEP Top aai pres a se BE FEE ir 6» tt att ine oo cnine AEE class designer understands the cloning process. Objects are so'parand about cloning. that they jenerate a checked exception ian object request cloning but doesnot imple. ‘ment that interface. hallow copy) implementation of ese is adequate, you still need to Ne interface, redefine clot be public, and call sper clea). Heres propriate for fra classes. Othervit, itis a good idea to leave the thos speci- That gives subclasses the option of throwing a ClnsetSporedEception iF ange rei ope they car support cloning. [Y] emorencii sesonnismh twcsmimieetsvercieocis | Sse inom con youronm th you pe sul Some vated iplemen another eto fr abe whvard, bt you nani te sane ‘The clone method that you just saw ads 0 functionality to the hallow copy provided stoter med At sy ate doning sles Peet ofthedses in the andar bay eprom in isting 6-2 clones an iy eth cusps the lve reste ey metod anges the state ofthe Ney field. Nether mutation affects the original object because has been defined to make a deep copy. oat poses se [oars UT 39 aay ‘op pags eyes os nod pur years uN ai 125 NOK SHEN B DANSUOD MOK yy, ney spop an atepsn eo no ye os puoses Kz pogou.ag or APE RD NOK UR po ‘Ponteruob uzecdasd sno goed» 9fdusena 203 poede> sw [eADIUT AUT 2a, Toyo agen ues nok TAIN a IA Sse aL eEuTUED AREPeM UE eM ay ‘aonenate sda 7g TERNS e29pFRIy an sapere nuauoian oy Mody uses YK OU 2A Na 9MeDNG TONDAOH Papas ‘Graan nus a0 poyoip s wong © vay 00. woRDS (NSA w A Knog -apdiaves so sundae yuna zooped © sanousts. 27000 PMOYE HR VORDR HN Apodg Oy ues nod mowed np wed peg ay 5 SuneNEsBosd ur Wsaed WOUND y ee, + Ges + hale, ota + oma, mes ‘ 1 yg Oa 6 hepa ype n 9s sepals soot Jo 216m sess lp = ome “saturate = a (ep ey pune 2 a een aS og an sprees pun ore fs suse ear pone vonezane ee [A] ‘A boun spote Sonn amare man we Smee ORR P BAD ION ese souuy por DEOL m9 HED Chapter 6 m Interfaces and Inner Classes very 1Deeconds, a message like ye tine Tu Jor 13 Z3:2888 FT 208) lowed by a beep. tung 6-3 ps the ines and its ction Listener to work Aer the ier i started, Tea am puts up a message dialog and waits forthe user o click the Ok button to the program ait forthe user te current time is displayed in 1-econd How do you tel the timer what it should do? in many programming languages, af; sbjecto more lexle than psig fancon becuse the chet can radon als went when running the program. The “Quit program?” dialog box appears right he fst times message is displayed after 10 seconds. hatte program imports the jaax.swingTner clas by name, in addition to import: frags ad jv. This breaks the ambiguity between jv og Timer and unrelated cass for scheduling background tasks. Systo.ent(, ' 2 Gs Trine pone itso ects op pasn 39 ue> 0 are Lag, sou sous pu: ‘odors Susop 9 a4 Jo sqqetn poo sso ue> pap 8 ban suowsoe 9 des 0} quem Kou sropeas ysrueonbs sassy Jeo! OW paretsuen are Lamy moy aos 0 Sossep sou apie adam 'p9z ABE UD SINIAS + whuow sompaqusass ‘692 ed wo Sus + oy senoep aM 967 ed uo EIB + oeonp sons sop sop xenuks pads om waaco2M eye EIUD + “seep Ino IO peo muma vesesomoe ag sep sounds wane MOK Gz aed wo BRIE + “says yronas on 24d xaycu0> soyyes sp dn year TM 3M, _gm norm speqto app owen ned uous ApuEY ae Sssep seu srouhueny + aBeyoed outs of 58 AYO WO] PPR AAU SHEP a > -ayeapd aq asmaratno pom ye eep BupPNPUy __prayop are xy yps o adooe 203 wep am SNE UO SONAL SP + svorea 2939 18 4), 2) op o 2H nok mem Sua SHEP sBIROUE apIFEFOUGEP HEA SD 8S HH OY ‘s9seufQ 2900] ‘punos dooq ess Ea s3588/D sou) “esse sous pue SoepawuT m9 side Chapter 6 m Interfaces and inner Classes Use of an Inner Class to Access Object State ‘The syntax for inner clases is rather complex. Fo that reason, we ute a simplebut artifical example to demorstrate the use of inner clases, We rfactor the Something suprising is ping on. The Tie named bet Instead, bp refers to the field solic object that create this Tim Feiner. Thisis quite innovative. Traditionally a method could refer tothe data fields cf ‘object invoking the method. An inc cass method ges to access both its own data Bas ‘and those of the outer object creating it For this to work, an objec of an inner las always gets an impli reference tothe obs that created it. Gee igure 6-3) This reference is invisble in the definition ofthe inner cass, However to illuminate bt she reference to the outer object outer. Then, te arioerertorved met aces ee ‘adding a parameter for the outer late reference. Because the TiePriater mi theses a default constructor, generating igure 6-3 An joner clas object has a reference to an outer class object sustate the mecha- Again, please note outer isnot a Java keyword. Wejust use ‘sm involved in an inner clase. inner clas isan improvement, There sno need to provide ily iene other cae seep samo ap o adeos a4 aptsino si20 sm ‘uu, orto anour eq» ey aouarapar syne ap op xeuKs sadoud ap ATeRIOY "21 “es a soup sou ojo sounsapar ese ZnO mB pueda en "uoHO Buypadeid sasep[9 JoUUT of sommy xDpUfig |eds Sa6se(9 12uUy pue soepiou] m9 saadeyD Ea Chapter 6 Interfaces and (nner Classes Are Inner Classes Useful? Actually Necessary? Secure? and security By adding a fotire that nt and interesting rather than needed, has Java ‘started down the road thas alicted co many other languages? While we won't try to answer this question completely its worth noting that inner ‘lasses ae a phenomenon of the pile, not the virtual machine. Inner clases are {nap private ClasNone (Fo nes ao the compiler has generated an additional instance Geld, ti, the outer class. (The name thsi synthesized by the compiler—Jo your code) You can also see the TakingCec parameter for the cot 1f the compiler can automaticaly do this transformation, cou the same mechanism by hand? Let's try it, We would make ‘outside the Talkinlock clas. When constricting a Tirsfin reference ofthe object that is ceating it ct we pass it te this vewrcios EEE “Ths, nner asses are genuinely more powerful than regular classes because they have ‘more access privileges. ‘You may well wonder how inner classes manage to acquire those alded access priv Notice he static ae metho tha the compiler added othe outer clas. tetas the ‘eo eld ofthe objet thats passed as a parameter. Tenner dass methods cll har metho, The statement 10d ofthe Tineriter clas fetvely makes the following cal: ‘eu porgaut unsaxp jo geen seusered O2qauy “sued sup vy Ie PoeUI UES ‘Sn poe poureas 5) 19am oxy ao;NsUOD any oe 04 passed DURES AE SA ssep nuzaip yo opnsysucn ap 099 © Ag PORTER dana poxqau ony uaey ssaNNe UBD SED apsino arp tox wap Aaordato> ne ox arnt 9oaqq ong 0 paras sh | yraads ssn3e we ie patesop S980 a pe no ge uy fo. nok “ajdusexo -pene ropun ssep aig e oBeyoed oases ana apie paved 39.0} pooU PROM IPOD PETE aap Gmnaira oeped ane epoupaue seasoe arora senesog OPO N2y e sn faye ssepezonpoxd str 09. ue sy sp Jo aIMANS ap UA TEE] are ays supe aad} pOU=UT eae oj aurea © ours egsn2 28IM0> 30 ‘Yay ded ead a Dead OH POAT ASE ‘aot of aya auceibos 20j rapes Ase UR SESE F924 NOK LYSE AAIMIOS ESR 5] See UU) sassep JouUy pue SoOeHaI m9 sondeHD Ee public void actinerfored at. et Actenvt) fim torte vase, Fil ? "Note the totems parameter tothe constructor and the lites instance variable. When an nod j syepp sou sHOXLAUOUE ure ipa uresSloid pop SupsTes a4 203 apo samos syapduaoo avg sureyuo> ¢-9 Buysr] “sang 9909 ‘ae paeooseo, ov doy Adds xy nop nok peg sun save Boas au Aqpeee 3 9 Su ast us some say OAL Ui 9p aS pect aay « eu nONS seep DUE 3O; pons UNM HOOT AeAoNA Lope> ‘asssnjgo Suman jo dem yeas Katy ane ao sopryeaidv eosses toa soouasvsue Sey -peuyop Sings sep zou mourhzove we un 20819 Suqvado we £qpomonoy sy round wononseuoo ajo a =p np Bunpioea sep sau snoehuowe ae Jo algo we Jo woRANIRRUED aA PUR SEP Fo -palgo mau yo uot ansgsuoo ty uBSauD9 aoURT ap 995 ofA} YOO OF BAP, NOH 4 meron Osi 0 se covoquated jo 20 © Sddns sons nok “me -sasapysrjourezed vonpnasuo> re aay ONURD omy we sue dua See ‘ue sana ‘rena uy 3onNSuED ssyE.adns ao Vani are soameTed UoNPNS woo ip ‘peois ‘aume ou Sey Sse oA Pu ‘sep Yo SUTEU TR Se URS 2p qn soponassieo Jo sureuaup aang S20} 9nNFUOD ane LRT Sep 12 SNOUUOUE UY ‘Sep Yep spualxo ssep za oMp “Uae sep wg umo ad dng 30 =PePOIUL EN SHOU -erdun ssep souuy ay ung is} U0 /Dy se ips oeprap ww 94 Ue ads 09Fy fi ep psp Se : (eam emus wu sixes on Te Uy Sep ampere a9 oie IM Chapter 6 Mt Interfaces and Inner Classes Here sa typical exemple of where you would want to do this. Copsidar the task in an array. Of cour ne eet must un ors Veen ahve dng ‘air that holds two values: Hd a (ren Firsts} tue sz} = However ualke the inner classes that we used in previous examples, we donot want eve ence 10 any other object inside Pair ebject. Thatteference cen be suppressed arng te inno class satic NOTE: ruse a sats rer Gass whenover re inner cass does oot need to access at (nos cass object. Some progres uso th term nesteéclassto deserve stare 4 —<—<—<— —$>——— NOTE: ner caso hat av declared rca an terns are automaticaly static and Ww pati sigs contin te complete soe cde ofthe ral en thenestod Fotr a apon ajsaund sues3oxd auiosUa}gold Sp ONO. vueiford Sunaanse w se nau vauyop oy poou nog 2oeFD1UI UE RENEE wonogas oon so poss seesevou au 250 Ade ued NOK’ -unygond anougp 4 Segura ado ye mou you Keur MOK ‘satu aZOw 30 au SUNDA NT NR SHEP @ 4022140 ERRMRMAE AERA HARA KGAA ES UATE Teese wana popes 250m ple pod Team) a ue Hea wD HHT Chapter 6 mt Interfaces and tnner Classes Chass objects, one for each interface tobe implemented. + Aninvoration handler ‘There are two remaining questions. How do we define the handler? And what ean we do Sbjct? The answers depend, ofcourse, on the problem that we ‘mechanism, Proxies can be used for many purpases sucha Routing method + Associating user interface events with actions in a running program: and Now whenever a met em one often icles on ray the mato nae pr didnot -pouyopariou ae (5 2g 22ypEEY UOREOA Ig UO ZA ‘seep alg ap JO spouau EN p valen 20 Jo sport agg 25a Spon Avodah, uae ip pode pe 3 “1-9 Seer wr unos wesSord ut spago gutta pocord 9m won dln _Srpue oopesont or pay og Bsn IED faead = 0 LO Peo uoTeayeepfeoomppe hay ssejmcins fey an PSP spas MAPUMG Loo apppu suet oue Sy Sh Se Axoad Y ha Seep aN PURO See Seo ape runs _p ese ip Sense aaa ha poy are La 90 ag nog -ureaSond Sarna Ay 4p 0 Peas are Sssep SHON Aq -doud sa yo 0s lan0 080 oem 3 ORE UY sasseP Kod WRS DAE NOK agy sosspig fixasg fo soyiodoug poncoad sCeane are sposp _ueyao ‘uoRoF pou 24g UI 296 YN NaA SesoeprqET ges) 2 OF BUPA 9M SOP a oSnoxp uoaa porcod ey porpaur base sig eI MON "doy Asano UF OY ATTRA reas ap Sumaro hh ng uo ty sey nese press Area 4 ON 395 UNO, ‘SSE 13UN] puE sIOeUOTUT m9 saIdeHD fs Chapter 6 Interfaces and Inner Classes “Therames of proxy clasts ate et defined. The rats clase nas tat begin with the sng rem Theres only one pony as fora particular classloader and ondeed set. : Ta aigyouca he soroyioune meted eis he sane closer nd Youcan als obtain that dace wi sin Sun's vin machi ifallintefaces that the prowy css implement epi then te procy cts doce not belong to ay pts package Other ah Chapter GRAPHICS PROGRAMMING Aa aecaad as we already mentioned, proxies arean advanced techn advanes ique that is of interest mainly © ‘a0 builders, not application programmes. You te now ready to goon to learn about ‘raphics and user interfaces, starting with Chapter. IymopuoIne SANS (CREATING A FRAME PosTIONING & FRAME DspLavins INFORMATION IN A COMPONENT |WorkaNG wil 2D SHAPES Use CoLor Use Srecial FONTS FOR TOT Disetann IMAGES [Pay pue YOO] os zz poe Fz samy suresfaid Sums Suga sat swaigond ¥aqi pmo sayy peods ony epee wopoL sj oumpedea ino LW au Aq posn syuavodines pateg-rand 349 we W39 ‘uo seadde 0 yao eyatausos 39 oe Showofa adem oan Pose Su “Dupuy va sens "p40 Cayop.yn a suBUEIPEN Burp sa veo dorppueSup + pie ay az ay Armes op nq suauodns Sung af sori Sota ong a Sue Pee a ays Bapnponiey ‘hag ese ut Krergy prepaes 4p Joye wausse9 pue 1 Ha warvon ue se agape sm Bug Bin, ae 9p lo asl ses EN Bupa *peoidde sep payed 0 adeonan Wien poys0% ung wo ea uso a “pad (erga seu ov aus a paneyag pie payooy saps a adeoseN ‘SMT MOP “sin 2g} uo Fed oy pus swopum dnd on dom ¥Sea tans apnopin PON ‘nn wos; paxnbasAyqeucuoiny Ao ay, Sop UEIg Oh ptked a>. "%0 Os PE sspunt'suoyng se vons ‘uous oem sn wpeordde oaayep Aas PISAIAR (esse wonepUmeg Taub) D3] ap p> Aa Area De pana SeeDOIN SEE HL -casaydina Bacep 990 a, pare densuop soppexde twronad yp uo suowxaydde aa sono PopaoN 9 ore cos ssodoyanacmisopeyd ara 9 uo Aseag]ugmoen Lay oS Tnadfipanon arp Sassaidap soy ods9 0} ano Py ORE seg Jo SEN -aqeoosouny fo pup} aeey oxy pip 30u Suoseagade UsouESRy 30 eOp ANE ss use 60} 14 rp Aldus Lay ss uname swoon nD mesa sy spoowdce "ovr n> ynmc, 8 oy Has wo pos ee aod wu ohn amy “sty AsORUDE st 30 Smaps Sap Se suauodtd> ea sn fo woR=OON eT cP 3804100 Guope/ Tx tons) spun TeongGer# sos onoasy} pend ‘sn ue oatoundsa aygexpad pu aust esian ane ato pe se _csuoagd neagip vo aoweye uESouAAT speAs ay UD spy Yon PUP Sagas ‘sms yons smut ep) URIS ae Zen ae LO popLodop eg dreary ojqenod Amel eos oF FOU AADIPUMY He NTS -acide sures uber nq svoREOTsde apr cj om poysoe poonepoceg aod oy, cates um 060 aay, weBens pase 5.5 [pov IND anew ayo} soregag pur woREAD ZMH Taye sje Ase av sea, Suma Beso offs Uns yore seg SSP €PEUNEUOD Hi aRPOLN SEG Buyag Bupnpoxuy -saidewp asin doys Apes wes nok ZaxmuesBord yn Sumas wt poysasoy ou au ‘sonbenpy Sumumresford sone? payernenydos tour ‘gaa 30} semuasso =p mou] TEA ROK Ide saNB AHH YEA NOK va FOR surexBoid earl Suni oj pecs ayy oak Si scone OR, “aed gos op aan pu hem nn 20m op sed wepoy MONIKA Sas OUI eye sors gy sain yoru ev senso tS uty Pun oye ascimiene eg naetndojam cnn die ermal ne Taanceiong Oude wZ ade Chapter 7 m Graphics Programming, Furthermore, Sun developed aplatfo-independent look and feel that was called Mal” unl the marketing folks na 0 daa —ecMcase Creating a Frame Ea ications use the nativelook and feet of thee plat- sty ook and fel. As you wil sa in Chapter, tis very easy to let your users choose their favorite ook and feel Ivodueed a lock and tel caed Synth, at makes this process easier. In ‘Syat, you can cine a new look and te by proving mage les ans XML Cecripor, bout cing any programing, you have programed Microsalt Windows applications ‘ow about the ease of us that comes with the graphical sand resoure editors these products provide. These foals let you design the viul appearance of your applics. we go over the most common methods for working with Swing Frame. a spe program that dieplaysan empty frame on the seen, ue (tated in Figure 7-4, iy sae pm 3 snopuyn 2 pou sxsw PIII G5 36 wey pur ‘soso voqeosndp uote sem bung ie AS "U0 8 CUB ‘Se 31930 popu guiness popaermaty ANH MOMS EM EH N30} Moje oun a ovr ean ppeen ate a meel2ord si} casa sins oar 1 Ad renmuorne os snp 263 Boras Aa eqs ag SUE ptr, ren yu sop eu ok ng ep _Bomatg ung umppn tours no Ags a oo sot ‘ealyope wwsiend opi Os po nok sate Te ln aeRO ao "Con wrune aD MRRAEOEN Ny Rowse cag esr om soraeyoq ang 2972¢ of 3526) wwesToud ang em am ‘wresBord smo Ed ey ng use = uonENy a oe eBsOP Joan 2g) aya uae PINOY YH BUYAP 2M DON, vuenlord Bunge reys.0 pasn 4p VOREHUEDD “Seu eg soprsu0o Adu prnoys BOK AOU 104 "FL NEN UI SEP a ‘ong ana any uy suawsayers syne oy posn s uauiBey 9poo Binmoqo} a abepron Josh otf 0 saONSK9H pe SIP asnou se ys quand sexed IH pean ax peo psp wo ap ox; paanSiguod oq jn sys9uodusco sares@oxd Su £299 wt SSaNPpe OF poo aM ey Sse JEU Om He AL rsp Aue ayy su“ QUE x NE az 3 as © ayo 94x 0x 030228 s83]260 JOU prsan sys won ary gs tof Ano ut oad 1 Tendo} ORR sepanpavon's Sunss suoste (ouoienf2eg-afoped o> ou ofepped wpa eef hoa reetawedepedagy soprd auc weat ag poe dan oxsep Bag aL ‘Kaun wean ng yBrong pos 72] ‘Boyummeddoig soydeso mC sordeyD BD cere» cic resin ratiingarame EE ‘the top left comer is located x pixels across and y pixels down, whee (0, 0)is the top-left ee method in Cpe ets you resize and relo- Jnitaiztion statements, the ain method oi te the program, just the main tread. The ev live unt ii terminated, ether by closing the frame or —_—_——— SENT ae a pian damon fF ene twough fhe maiz ofinertance most ofthe methods or working with thesize and postin ‘fa ne come fom he various superdases of rae Flere ae some of the mostimparat ableby the user Figuze7-5 iDucraes th inheritance hierarchy forthe rane ass. Migwe7-6 Inheritance hierarchy for the: soponent clase . ‘ame and co ASE and Swing ca > settcaione, 1) -apou was ut woneaqdde nok ayaxa naK 92] OFT SEP HUME Ee Aeidsp 29 30 su0ssounp 29 puy 01585529 aap asn swoon Av dsp dynamo aByurape sozer Fe ‘ood sy Joy gy Soouaraaug auf 260 oh sy cape uogeaidde a9 sets mod uate spunog aso a:c¥ar Put HORE Jo atic xg some pu suokood soem kp NOY JaquUaNIS 0 ep! POOR wos Ka caw =) aqueous Ads ws nok AG eae 0 Sy 32 wnUIKEUE aH OF wEOUd e30 neg tue ayy 35 0} uourUNOD BAND st 3p SUUOUID | ‘apn as2q THA suey oy), Is sure a eso} POU “spray pa ue suoR|NG se yore syuouodiD PrEPUEYS Ayo SHIETUCO HRY; MOK HE g sxe wise Supp 205 sda JeUDRIppE ma © aaa ‘xp oy vom Sed esfond ag ums nok ua “umessosd aad caviszry seid nok uaqee S960 28 ue nod pu snopunas ax yo z0ur00 4-day au pake( dap ss ‘Notne 10g sooetd snopen uy uoot a a eo Rod "rss ueado mk wo Bujpusdeg aR RD aL (EAs ‘mos fundimp esse ionnimenb ges ap 18> Says 2uropoy tp ase ons was ah susaz3s vornyosa2-ySqy @ uo duu ‘eax 300 That aos doydey © uo amu Sjoo| eyR MopuTO e :A(SupLO: an sores nein 9p09 asm ple ude!8 3.950 ax Jo BoRNIOSeL XA pAK pynoys mOK aa 22 Sao8u4 poy a suyRP spoypous om: BUIHOHD nq od 30 sopodoad 20g suonuaao ‘sueip pa ap rasosoy yeh Samsopuun i SuxKos syns sow op foun SEHR PS SSienuy ou eyase pu peor ent Saxy eynay“Pansouraiduy are Spowau 725 PU abn mon (99 30) UD .NOP 2 fxd a 18 9m ua uaaies s298n 21g UO 898 aah ae any fo Suodaad neo 204 2609140} 01185 10 15 3 ‘aL dw pe ase ey A Ssep sess 30 PON ‘Bamoqoy an se yons sme ioe /rana wt auto sasseo uuaduIO yo spouu ATE sopiiadosg uns ‘auc ayo anger oreo susuneReLD 9a oumucd & ops sueueruoos9go 0) ‘gree woe a nek ey wane ou [7A] ng oyonmes vows er pees pup womens of saTeNDI000 BUH E104 -3ION swaps 32] ag) oss ¥25}0 2984 © jn you a) woResoraxp 721d wayshs Bumpin skp eopULN a {-ywounceyd open uo yoreo was upmopim ap an ued nos APPaneUATY ‘pareay e Suwon isog Baquuerdoug odes wc rdey> FE inte 7 w ents ragein facet ee EM siztcrraetest.jaa le property. Components ae initially visite, with the top-level components such as rare ‘maves the component to. new location. The x- and y-coordinates use the coordinates of the container if the component s nota top-level inPlatfore property. When the property i set before this the platform picks a suitable location property that determines the text in the tite bar fr the frame, ing} property that determines the con forthe frame. The winding yet may dpa the con as ptt ofthe ame decoration or in » Sheraton Ree heeeeYEREE HEME EUERE ED Seep JR UE PoXAA MDAC Ipsong pur naundanr spumpo eur ssep e auyap nok wavodHOD uO mexp OL "SEH ang sep es an oxen ju gaze a 0} suEduno>aBUIS& PEO} MEM B35 m0 up mije © 30 semponne EAE f2 amy ‘Suxopey a9 se wpns apes Buss ‘ued uous ayo} SHURE -oduans ppe nog ‘ures » Sums Wat ued jurtano ays raumuTeFond Hug Si? go soy ed UL BY Pee uraydu 0 pue aued yuaiuon pue 30g nous ban azn0e800 0} pan sp Agena nox Spa 99:27 36.040 35 SAUTERUOD 3g 01 FUESEP | ‘pasapisuco yous eu 7g aWsEY €ewUo Keren Soy opemieyey séudqp 2p ures VoL oma o-camfig wt uous 2 ‘our » ws aSescaus ayy Kepdp saidey un pipam se opens asus «uy 2pour ra 8 ,eer80%d plA4 OTH PION, Sader’ weap zope vpydunoce 104 uy e pseu; aoneursopu KEFSED Loy NOS HONS 94 "WORDEN Up yuouodwog v uy uoFeMLLosuT SuyAurdstC, poeydarp soures ong eu0yeq pay oq pownow sni-vonna asop 20 09 ap #38 Yes suoHEIO29p InoIpL pedeyasP ‘youre aug os stpodord ou way wauodwo5 & u; wopeuuoyuy Sudeydaig Sauuesdoxg Oude w 2 suey Chapter 7m Graphics Programming Displaying Information in a Component Each time a window needs to be redrawn, no matter what the reason, the event han- ler notifies the component. This causes the pietCannsen methods ofall components is calld automaticaly whene ‘you should not nterfre with Displaying texts considered a special kind of drawing. The Grghls case has adeastri method that has the law the string "Wt 2 ello, Url Pregrt” in our original wit don roughly onequarer athe way Sos and balay down, Aton eda ‘yet know how to measure the size ofthe string, we'll ddown—see page 213 for more on how text is measured.) Thus, our paintaxpnst method looks like this: amu ai any esa cog sara nie pu earn ocr ee Tq) espe eae epoqsed codes eyo sou poder Arma zen eal 'z1on LA! soepsaiy ates ata wouraidur esse: soso pu ‘soSterar sau wuasoidas oy sSessep are am -noqsed uy uomyse peitajo-nalgo we wy sadeysouowooS sozudai0 Sseaqy Cz eae[ ay °6 (gst) = 2 on ‘saanqeo} pobuvape 2x9 wo woREULOGUE a:ow 25 stmIOA Zep LAY podwe ‘249 995—Aresq gz Bae ap jo 54 ap YOO} AO 9 Typ SAU svORE reoryde yee mptomod e sususmdun ypu rea G7 man 2 POONPORLT La sade ap aye0230uURD NOK ple SaLDPAA 2 ‘en ose nok aydanxa 204 poy £98 are sionnsado Suerp aoxp IMG WOOS PE “soe jue st mezp 0} spor ys Dye ag DT Rael Ms BuRES sodeqs az qi14 Supyom (onda ue an perpen _anog) suey o ed yuou0o ax 0 bouoduoo waa ain sa | x BaynareBoag Dydeay m2 aMIdeyD Chapter 7 i Graphics Programming point coordinates. In many cases, th tospecify your shapes in coordinates ters or inches) and then translate to pixels. The J Ft quantities for many ofits intemal floating-point calculations: sulficient afterall, theultimate purpose ofthe geometric comput However, manipulating Mua values is sometimes inconvenient forthe programmer ‘because the Java programming language is adamant about requiring casts when nt Fat values. For example, consider the fllowing statemeat “This statement does not compile because the constant L2 has type dbl, and the com pier i nervous about les of precision. The reed is toad an F sux othe losing ‘ond camp and use dale coordinates whenever we ‘The Ubxary designers chose curious and inially confusing, method for packaging these choices. Consider the lscagleit class. This isan abetrac las with two concrete Figure 7-8 shows the inheritance diagram. Working with 2D Shapes EI ‘Thats, you only need to use the pesky ner classes when you corstruct the shape ects. ‘The consruetion parameters denote the topleft comer, width and height ofthe recungle 20 methods use dase parameters al return values, For ena 3 dbl value, evenif the wiluis stored asa lest a actaglelD oat sae poe ‘gor PEN ‘ox 050 222010 yoy YH ‘aides 205 ure stout yay-doy a yo sa) ‘gprs 04 pao nox ronnsuo on adans ate algo ty Aer « pun porous are soosep Aon] ‘po parargeg ain smasMoy seem adeys xp oom sessep grtiny pu Sapa gua sod e pur of@uepar «2251 Ye ig Pues UL IE _oyyssep adeys.atp 01] pany ws2q axe 97 eanf oy seep K2e89| 30 cn0>« Kyou ‘algo gauge sanju ay suas yA porRaM sumUE BOW Bum sR JO UI sg pes ya) gine pu Yonsey es “Wp NAS PNAS Se SPONAL Yo ons aA Soeur ‘sadeys asa oy vou are en spa\RoN 9 Z240SOUyap eae, ‘sedme wa yo opreioes Suypamog oud 6-L Om ‘e-zaindig one) afuanns Sapunog ancy Kang 909 tefueos you are sosda ‘pany ‘eg seroeyseypiedne uotannon a wos Boqur Ogee UE GIB! Seep aL ry asso opts enon fngr—Ur> ne voy 2640 Cs BEN NOK TH ISCOOTS "9 atin qua yeooe spogow pu esas Ase Soren pub ehredos im UAL sea ee mn HH | Date} alge But Foen faa sooo wo a ‘aaty ea» 6 geesg ndvaqrw oy oy aH agar ortog ny SOSSEQAE IL sia ssowypINg YHA ‘se sssep ads sano ap 305 spor sesee> past) 21 05 POSTON nl 2m UM ensesueo c S8S60R Ly {a Bsn repsue0 wen of wus eplgo odous Jo spurte Sungeuco wre nok one “s+ gabon sen oy en Bapeep reo see ede o( peg incon FNS ——_—_——_—_—_—————"= ‘Tamuwerdoag SyyderD w Z vedey Ei Ea ‘sadeys Gz WIM BupHOM.

You might also like