1. Trang chủ
  2. » Khoa Học Tự Nhiên

Head first java kathy sierra, bert bates 2ed

691 3 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 691
Dung lượng 34,87 MB

Nội dung

:PVS#SBJOPO+BWB‰"-FBSOFST(VJEF ND%DITION #OVERS*AVA -FBSOIPXUISFBET DBODIBOHFZPVSMJGF )FBE'JSTU +BWB BLF+BWBDPODFQUT TUJDLUPZPVSCSBJO 'PPMBSPVOEJO UIF+BWB-JCSBSZ "WPJEFNCBSBTTJOH 00NJTUBLFT #FOEZPVSNJOE BSPVOE +BWBQV[[MFT BLFBUUSBDUJWF BOEVTFGVM(6*T ,BUIZ4JFSSB#FSU#BUFT www.elsolucionario.net Table of Contents (summary) Intro xxi Breaking the Surface: a quick dip A Trip to Objectville: yes, there will be objects 27 Know Your Variables: primitives and references 49 How Objects Behave: object state affects method behavior 71 Extra-Strength Methods: flow control, operations, and more Using the Java Library: so you don’t have to write it all yourself 125 95 Better Living in Objectville: planning for the future 165 Serious Polymorphism: exploiting abstract classes and interfaces 197 Life and Death of an Object: constructors and memory management 235 10 Numbers Matter: math, formatting, wrappers, and statics 273 11 Risky Behavior: exception handling 315 12 A Very Graphic Story: intro to GUI, event handling, and inner classes 353 13 Work on Your Swing: layout managers and components 399 14 Saving Objects: serialization and I/O 429 15 Make a Connection: networking sockets and multithreading 471 16 Data Structures: collections and generics 529 17 Release Your Code: packaging and deployment 581 18 Distributed Computing: RMI with a dash of servlets, EJB, and Jini 607 A Appendix A: Final code kitchen 649 B Appendix B: Top Ten Things that didn’t make it into the rest of the book 659 Index 677 Table of Contents (the full version) i Intro Your brain on Java (EREYOUARETRYINGTOLEARNSOMETHING WHILEHEREYOURBRAIN ISDOINGYOUAFAVORBYMAKINGSURETHELEARNINGDOESNTSTICK9OURBRAINSTHINKING h"ETTER LEAVEROOMFORMOREIMPORTANTTHINGS LIKEWHICHWILDANIMALSTOAVOIDANDWHETHERNAKED SNOWBOARDINGISABADIDEAv3OHOWDOYOUTRICKYOURBRAININTOTHINKINGTHATYOURLIFE DEPENDSONKNOWING*AVA Who is this book for? xxii What your brain is thinking xxiii Metacognition xxv Bend your brain into submission xxvii What you need for this book xxviii Technical editors xxx Acknowledgements xxxi ix www.elsolucionario.net Breaking the Surface Java takes you to new places &ROMITSHUMBLERELEASETOTHEPUBLICASTHE WIMPY VERSION *AVASEDUCEDPROGRAMMERSWITHITSFRIENDLYSYNTAX OBJECT ORIENTED FEATURES MEMORYMANAGEMENT When a Dog loses its Dogness When a Dog won’t act like a Dog I don’t know what you’re talking about Sit? Stay? 4HEPROBLEMWITHHAVINGEVERYTHINGTREATED POLYMORPHICALLYASAN/BJECTISTHATTHEOBJECTS APPEARTOLOSEBUTNOTPERMANENTLY THEIR TRUEESSENCE4HE$OGAPPEARSTOLOSEITSDOGNESS ,ETSSEEWHATHAPPENSWHENWEPASSA$OGTO AMETHODTHATRETURNSAREFERENCETOTHESAME $OGOBJECT BUTDECLARESTHERETURNTYPEASTYPE /BJECTRATHERTHAN$OG BAD L public void go() { Dog aDog = new Dog(); g = getObject(aDog); g Dog sameDog } bark? Hmmmm I don’t recall knowing those he methodthe t h g u o h t n ve og n’t work! E ery same D This line wao reference to the evturn type Object rned returned referred to, the r you assign the retu argument compiler won’t let bject means the to anything but O reference public Object getObject(Object o) { a return o; to the same Dog, but asNote: e nc re fe re a ing rn tu re al We’re } This part is perfectly leg return type of Object e get() method works when you have this is similar to how th ther than an ArrayList an ArrayList File Edit Window Help Remember The compiler doesn’t know that the thing returned from the method is actually a Dog, so it won’t let you assign it to a Dog reference (You’ll see why on the next page.) DogPolyTest.java:10: incompatible types found : java.lang.Object required: Dog Dog sameDog = takeObjects(aDog); error ^ GOOD J public void go() { Dog aDog = new Dog(); Object sameDog = getObject(aDog); } public Object getObject(Object o) { return o; This works (although it may not be very useful, as you’ll see in a moment) because you can assign ANYTHING to a reference of type Object, since every class passes the IS-A test for Object Every object in Java is an instance of type Object, because every class in Java has Object at the top of its inheritance tree } 212 chapter www.elsolucionario.net interfaces and polymorphism Objects don’t bark 3ONOWWEKNOWTHATWHENANOBJECTIS REFERENCEDBYAVARIABLEDECLAREDASTYPE /BJECT ITCANTBEASSIGNEDTOAVARIABLE DECLAREDWITHTHEACTUALOBJECTSTYPE !NDWEKNOWTHATTHISCANHAPPENWHEN ARETURNTYPEORARGUMENTISDECLARED ASTYPE/BJECT ASWOULDBETHECASE FOREXAMPLE WHENTHEOBJECTISPUT INTOAN!RRAY,ISTOFTYPE/BJECTUSING !RRAY,IST/BJECT"UTWHATARETHE IMPLICATIONSOFTHIS)SITAPROBLEMTO HAVETOUSEAN/BJECTREFERENCEVARIABLE TOREFERTOA$OGOBJECT,ETSTRYTOCALL $OGMETHODSONOUR$OG 4HAT #OMPILER 4HINKS )S !N /BJECT o D og Object When you get an object reference from an ArrayList (or any method that declares Object as the return type), it comes back as a polymorphic reference type of Object So you have an Object reference to (in this case) a Dog instance Object o = al.get(index); int i = o.hashCode(); Won’t compile! t objec sa Object an call s s la C e c This is fin() method, so you t in Java hashCode hod on ANY objec that met o.bark(); o.b o.ba Can’t this!! The Object class has no idea what it means to bark() Even though YOU know it’s really a Dog at that index, the compiler doesn’t hashCod e( ) The compiler decides whether you can call a method based on the reference type, not the actual object type o %VENIFYOUKNOWTHEOBJECTISCAPABLE hBUTITREALLYISA$OG HONESTv THE COMPILERSEESITONLYASAGENERIC/BJECT &ORALLTHECOMPILERKNOWS YOUPUTA "UTTONOBJECTOUTTHERE/RA-ICROWAVE OBJECT/RSOMEOTHERTHINGTHATREALLY DOESNTKNOWHOWTOBARK 4HECOMPILERCHECKSTHECLASSOFTHE REFERENCETYPEˆNOTTHEOBJECTTYPEˆTO SEEIFYOUCANCALLAMETHODUSINGTHAT REFERENCE Object Object equals() getClass() hashCode() toString() D og objec t The method you’re calling on a reference MUST be in the class of that reference type Doesn’t matter what the actual object is o.hashCode(); The “o” reference was declared as type Object, so you can call methods only if those methods are in class Object you are here4 www.elsolucionario.net 213 objects are Objects He treats me like an Object But I can so much more if only he’d see me for what I really am Get in touch with your inner Object !NOBJECTCONTAINSEVERYTHINGITINHERITSFROMEACHOFITS SUPERCLASSES4HATMEANSEVERYOBJECTˆREGARDLESSOFITS ACTUALCLASSTYPEˆISALSOANINSTANCEOFCLASS/BJECT4HAT MEANSANYOBJECTIN*AVACANBETREATEDNOTJUSTASA$OG "UTTON OR3NOWBOARD BUTALSOASAN/BJECT7HENYOU SAYnew Snowboard() YOUGETASINGLEOBJECTONTHE HEAPˆA3NOWBOARDOBJECTˆBUTTHAT3NOWBOARDWRAPS ITSELFAROUNDANINNERCOREREPRESENTINGTHE/BJECT CAPITALh/v PORTIONOFITSELF Object A single object on the heap ) d( g () has h ) de( r () s () la rol Ai getC nt ) s al () Object s( get equals() getClass() hashCode() toString() Snowboard inherits methods from superclass Object, and adds four more equ Snowboard turn () Co rin t oS t sh re equals() getClass() hashCode() toString() loseC o Snowboard turn() shred() getAir() loseControl() Sn ow b je oard ob ct There is only ONE object on the heap here A Snowboard object But it contains both the Snowboard class parts of itself and the Object class parts of itself 214 chapter www.elsolucionario.net ... POUNDS MAKEYIPPYSOUND ELSEv,ETSGOCHANGESOMESTATE pass-by-value means pass-by-copy copy of 11 00 00 X int foo.go(x); x 111 00 00 Methods use object state (bark different) 73 Method arguments and return types 74 Pass-by-value (the variable... MAKES*AVASOCOOL$IVEIN Virtual Machines The way Java works Code structure in Java Anatomy of a class The main() method Method Party() aload_0 invokespecial #1 return Compiled... to an int with Integer.parseInt() 117 Exercises and puzzles 118 Using the Java Library Java ships with hundreds of pre-built classes 9OUDONTHAVETO REINVENTTHEWHEELIFYOUKNOWHOWTOFINDWHATYOUNEEDFROMTHE*AVALIBRARY COMMONLY

Ngày đăng: 16/10/2021, 15:29

w