java in 60 minutes a day - download.e-bookshelf.de · richard f. raposa java™ in 60 minutes a day...

30
Richard F. Raposa Java in 60 Minutes a Day

Upload: others

Post on 16-Jul-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

  • Richard F. Raposa

    Java™ in 60 Minutes a Day

    b423149 FM.qxd 6/30/03 3:36 PM Page iii

    C1.jpg

  • b423149 FM.qxd 6/30/03 3:36 PM Page ii

  • Dear Valued Customer,

    We realize you’re a busy professional with deadlines to hit. Whether your goal is to learn a newtechnology or solve a critical problem, we want to be there to lend you a hand. Our primary objectiveis to provide you with the insight and knowledge you need to stay atop the highly competitive and ever-changing technology industry.

    Wiley Publishing, Inc., offers books on a wide variety of technical categories, including security, datawarehousing, software development tools, and networking — everything you need to reach your peak.Regardless of your level of expertise, the Wiley family of books has you covered.

    • For Dummies® – The fun and easy way® to learn

    • The Weekend Crash Course® – The fastest way to learn a new tool or technology

    • Visual – For those who prefer to learn a new topic visually

    • The Bible – The 100% comprehensive tutorial and reference

    • The Wiley Professional list – Practical and reliable resources for IT professionals

    The book you now hold is part of our new 60 Minutes a Day series which delivers what we think is theclosest experience to an actual hands-on seminar that is possible with a book. Our author is a veteran of hundreds of hours of classroom teaching, and he uses that background to guide you past the hurdlesand pitfalls to confidence and mastery of Java in manageable units that can be read and put to use injust an hour. If you have a broadband connection to the Web, you can see Richard introduce each topic — but this book will still be your best learning resource if you download only the audio files or useit strictly as a printed resource. From fundamentals to network and database programming, you’ll findthis self-paced training to be your best learning aid.

    Our commitment to you does not end at the last page of this book. We’d want to open a dialog withyou to see what other solutions we can provide. Please be sure to visit us at www.wiley.com/compbooksto review our complete title list and explore the other resources we offer. If you have a comment,suggestion, or any other inquiry, please locate the “contact us” link at www.wiley.com.

    Finally, we encourage you to review the following page for a list of Wiley titles on related topics.Thank you for your support and we look forward to hearing from you and serving your needs againin the future.

    Sincerely,

    Richard K. SwadleyVice President & Executive Group PublisherWiley Technology Publishing

    WILEYadvantage

    The

    more information on related titles

    a423149 RA.qxd 6/30/03 9:38 AM Page oi

  • 0-471-42548-6

    Available at your favorite bookseller or visitwww.wiley.com/compbooks

    Wiley Going to the Next Level

    0-471-42254-10-471-42314-9

    0-471-43023-4

    Wiley, For Dummies, The Fun and Easy Way, Weekend Crash Course, Visual and related trademarks, logosand trade dress are trademarks or registered trademarks of Wiley. Java and J2EE are trademarks of SunMicrosystems, Inc. All other trademarks are the property of their respective owners.

    60 Minutes a Day Books...• Self-paced instructional text packed with real-world tips and

    examples from real-world training instructors• Skill-building exercises, lab sessions, and assessments• Author-hosted streaming video presentations for each chapter

    will pinpoint key concepts and reinforce lessons

    Available from Wiley Publishing

    430234 RA.qxd 7/9/03 9:28 AM Page oii

  • Java™ in 60 Minutes a Day

    b423149 FM.qxd 6/30/03 3:36 PM Page i

  • b423149 FM.qxd 6/30/03 3:36 PM Page ii

  • Richard F. Raposa

    Java™ in 60 Minutes a Day

    b423149 FM.qxd 6/30/03 3:36 PM Page iii

  • Executive Publisher: Robert IpsenVice President and Publisher: Joe WikertSenior Editor: Ben RyanEditorial Manager: Kathryn A. MalmDevelopmental Editor: Jerry OlsenProduction Editor: Vincent KunkemuellerMedia Development Specialist: Angie DennyText Design & Composition: Wiley Composition Services

    Copyright © 2003 by Richard F. Raposa. All rights reserved.

    Published by Wiley Publishing, Inc., Indianapolis, Indiana

    Published simultaneously in Canada

    No part of this publication may be reproduced, stored in a retrieval system, or transmittedin any form or by any means, electronic, mechanical, photocopying, recording, scanning, orotherwise, except as permitted under Section 107 or 108 of the 1976 United States CopyrightAct, without either the prior written permission of the Publisher, or authorization throughpayment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rose-wood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8700. Requests to the Pub-lisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc.,10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, E-mail:[email protected].

    Limit of Liability/Disclaimer of Warranty: While the publisher and author have used theirbest efforts in preparing this book, they make no representations or warranties with respectto the accuracy or completeness of the contents of this book and specifically disclaim anyimplied warranties of merchantability or fitness for a particular purpose. No warranty maybe created or extended by sales representatives or written sales materials. The advice andstrategies contained herein may not be suitable for your situation. You should consult witha professional where appropriate. Neither the publisher nor author shall be liable for anyloss of profit or any other commercial damages, including but not limited to special, inci-dental, consequential, or other damages.

    For general information on our other products and services please contact our CustomerCare Department within the United States at (800) 762-2974, outside the United States at(317) 572-3993 or fax (317) 572-4002.

    Trademarks: Wiley, the Wiley logo and related trade dress are trademarks or registeredtrademarks of Wiley in the United States and other countries, and may not be used withoutwritten permission. The Gearhead Press trademark is the exclusive property of GearheadGroup Corporation. Java is a trademark of Sun Microsystems, Inc. All other trademarks arethe property of their respective owners. Wiley Publishing, Inc., is not associated with anyproduct or vendor mentioned in this book.

    Wiley also publishes its books in a variety of electronic formats. Some content that appearsin print may not be available in electronic books.

    Library of Congress Cataloging-in-Publication Data: See Publisher

    ISBN: 0-471-42314-9

    Printed in the United States of America

    10 9 8 7 6 5 4 3 2 1

    b423149 FM.qxd 6/30/03 3:36 PM Page iv

  • A Note from the Consulting Editor

    Instructor-led training is proven to be an effective and popular tool for training engi-neers and developers. To convey technical ideas and concepts, the classroom experi-ence is shown to be superior when compared to other delivery methods. As atechnical trainer for more than 20 years, I have seen the effectiveness of instructor-ledtraining firsthand. 60 Minutes a Day combines the best of the instructor-led trainingand book experience. Technical training is typically divided into short and discretemodules, where each module encapsulates a specific topic; each module is then fol-lowed by “questions and answers” and a review. 60 Minutes a Day titles follow thesame model: each chapter is short, discrete, and can be completed in 60 minutes a day.For these books, I have enlisted premier technical trainers as authors. They providethe voice of the trainer and demonstrate classroom experience in each book of theseries. You even get an opportunity to meet the actual trainer: As part of this innova-tive approach, each chapter of a 60 Minutes a Day book is presented online by theauthor. Readers are encouraged to view the online presentation before reading the rel-evant chapter. Therefore, 60 Minutes a Day delivers the complete classroom experi-ence—even the trainer.

    As an imprint of Wiley Publishing, Inc., Gearhead Press continues to bring you, thereader, the level of quality that Wiley has delivered consistently for nearly 200 years.

    Thank you.

    Donis MarshallFounder, Gearhead PressConsulting Editor, Wiley Technology Publishing Group

    b423149 FM.qxd 6/30/03 3:36 PM Page v

  • b423149 FM.qxd 6/30/03 3:36 PM Page vi

  • To my wife, Susan, for her motivation and support, and to our children, Megan, Ryan, Katelyn, and Emma, for letting

    me use the computer for hours at a time.

    b423149 FM.qxd 6/30/03 3:36 PM Page vii

  • b423149 FM.qxd 6/30/03 3:36 PM Page viii

  • Acknowledgments xix

    About the Author xxi

    Introduction xxiii

    Chapter 1 Getting Started with Java 1Why Java? 1The Java Virtual Machine 2The Editions of Java 4

    J2SE 4J2ME 5J2EE 5

    Downloading the Java 2 SDK 6Installing the SDK 7Running the SDK Tools 8

    Running the javac Compiler 9Running the JVM 10

    A Simple Java Program 10Step 1: Write the Source Code 11Step 2: Compile the Program 13Step 3: Run the Program 14

    Summary 17

    Chapter 2 Java Fundamentals 21Java Keywords 21Identifiers 22Java’s Eight Primitive Data Types 23Variables 24

    Assigning Variables 25Integral Types 27

    Contents

    ix

    423149 FM.qxd 7/10/03 2:03 PM Page ix

  • Floating-Point Types 29Boolean Data Type 30Char Data Type 31Strings 33References versus Primitive Data 35Constants 37Java Operators 37

    Increment and Decrement Operators 39Assignment Operators 40Shift Operators 40Comparison Operators 42Boolean Operators 43Ternary Operator 43

    Java Comments 44Summary 46

    Chapter 3 Control Structures 51Flow of Control 51Boolean Logic 52

    The and Operator 52The or Operator 53The exclusive or Operator 54The not Operator 54

    Boolean Operators 55The if Statement 57The if/else Statement 59The switch Statement 61The while Loop 64The do/while Loop 67The for Loop 70The break Keyword 74The continue Keyword 76Nested Loops 78Summary 80

    Chapter 4 Classes and Objects 85Overview of Classes and Objects 85Procedural Programming 86Object-Oriented Programming 87Object-Oriented Analysis and Design 88Writing a Java Class 89

    Adding Fields to a Class 89Adding Methods to a Class 90

    Instantiating an Object 92Garbage Collection 94Accessing Fields and Methods 97Using the Dot Operator 97

    Step 1: Write the Employee Class 97Step 2: Compile the Employee Class 98

    x Contents

    b423149 FM.qxd 6/30/03 3:36 PM Page x

  • Step 3: Write the EmployeeDemo Class 98Step 4: Compile the EmployeeDemo class 99Step 5: Run the EmployeeDemo program 99

    The this Reference 100Summary 103

    Chapter 5 Methods 107Method Call Stack 107Invoking Methods 108Method Signature 111Arguments and Parameters 113Call-by-Value 116Overloading Methods 121Constructors 125Default Constructor 128Using Constructors 129

    A Class with Multiple Constructors 130Using this in a Constructor 131Summary 136

    Chapter 6 Understanding Inheritance 139An Overview of Inheritance 139The is a Relationship 144Implementing Inheritance 145Instantiating Child Objects 146Single versus Multiple Inheritance 149The java.lang.Object Class 150The Methods of the Object Class 151Method Overriding 154The super Keyword 157The final Keyword 160

    final Methods 161The Instantiation Process 162Invoking a Parent Class Constructor 165Summary 170

    Chapter 7 Advanced Java Language Concepts 175An Overview of Packages 175Adding a Class to a Package 176The Namespace Created by Packages 178The import Keyword 180The Directory Structure of Packages 183

    Step 1: Write and Save the Source Code for Vehicle 185Step 2: Compile the Source Code Using the -d Flag 185Step 3: Write the CarDealer Class 186Step 4: Set the CLASSPATH 187Step 5: Compile and Run the CarDealer Program 188

    The Access Specifiers 190Encapsulation 194

    Contents xi

    b423149 FM.qxd 6/30/03 3:36 PM Page xi

  • Benefits of Encapsulation 197Understanding Static Members 198Accessing Static Fields and Methods 199Static Initializers 203Instance Initializers 205Summary 209

    Chapter 8 Polymorphism and Abstraction 213An Overview of Polymorphism 213Using Parent Class References to Child Objects 214Casting References 218The instanceof Keyword 221Polymorphic Parameters 225Heterogeneous Collections 229Virtual Methods 230Taking Advantage of Virtual Methods 233An Overview of Abstraction 238Abstract Classes 239Abstract Methods 241Summary 247

    Chapter 9 Collections 253Arrays 253Accessing Arrays 255The length Attribute 255Arrays of References 256Array Initializers 259Copying Arrays 261Multidimensional Arrays 263Example of a Heterogeneous Collection 265Overview of the Java Collections Framework 272The Vector Class 273

    Adding Elements to a Vector 275Accessing and Removing Elements in a Vector 277

    The Hashtable Class 281Adding Elements to a Hashtable 283Accessing Elements in a Hashtable 285

    Summary 290

    Chapter 10 Interfaces 295An Overview of Interfaces 295Declaring Interfaces 296User-Defined Interfaces 298

    Write the Interface Source Code 299Compile the Interface 299

    Implementing an Interface 300Write a Class That Implements Paintable 300Save and Compile the Rectangle Class 301Add the paint() Method 302Write a Class That Uses Paintable 302

    xii Contents

    b423149 FM.qxd 6/30/03 3:36 PM Page xii

  • Using Interfaces 303Exposing Methods via an Interface 304Forcing Behavior on a Class 310Declaring Fields in Interfaces 316Extending Interfaces 317

    Extending Multiple Interfaces 319Interfaces and Polymorphism 321Summary 326

    Chapter 11 Exception Handling 329Overview of Exception Handling 329Flow of Control of Exceptions 330Throwable Classes 333Methods of the Throwable Class 333Catching Exceptions 334Writing try/catch Blocks 335Multiple catch Blocks 337Handle or Declare Rule 341Declaring Exceptions 343The throws Keyword 345Throwing Exceptions 348The finally Keyword 351Overridden Methods and Exceptions 354User-Defined Exceptions 357Summary 361

    Chapter 12 An Introduction to GUI Programming 367AWT versus Swing 367Creating Windows 369

    java.awt.Frame Class 369javax.swing.JFrame Class 372

    Containers and Components 375Adding Components to a Container 375

    Layout Managers 378FlowLayout Manager 379BorderLayout Manager 383Panels 385GridLayout Manager 388BoxLayout Manager 390Nesting Panels 392Using No Layout Manager 396Summary 401

    Chapter 13 GUI Components and Event Handling 405The Delegation Model 405The Event Listener Interfaces 407Creating an Event Listener 409Registering a Listener with an Event Source 410The Event Adapter Classes 412

    Contents xiii

    b423149 FM.qxd 6/30/03 3:36 PM Page xiii

  • Buttons 417AWT Buttons 417Swing Buttons 418

    Check Boxes 421AWT Check Boxes 421Swing Check Boxes 423

    Radio Buttons 425AWT Radio Buttons 425Swing Radio Buttons 427

    Labels 429Text Components 430

    AWT Text Components 430Swing Text Components 434

    Lists 437AWT Lists 437Swing Lists 439

    Combo Boxes 440AWT Choice 440Swing Combo Boxes 442

    Progress Bars 445Menus 445Summary 452

    Chapter 14 Applets 457An Overview of Applets 457The java.applet.Applet Class 459Swing Applets 462Life Cycle of an Applet 465

    Step 1: Write the Applet Class 467Step 2: Write the HTML Page 468Step 3: View the HTML Page 468Step 4: View the Java Console 469

    The Tag 473Document and Code Base 478The appletviewer Tool 479Sandbox Security 481The Applet Context 485Displaying Images 488Playing Audio 490JAR Files and Applets 494Summary 500

    Chapter 15 Threads 503Overview of Threads 503Life Cycle of a Thread 506Creating a Thread 507Implementing Runnable 508

    xiv Contents

    b423149 FM.qxd 6/30/03 3:36 PM Page xiv

  • Extending the Thread Class 511Methods of the Thread Class 516Timer and TimerTask Classes 519Scheduling Tasks 522Multithreading Issues 526synchronized Keyword 530Deadlock Issues 532Ordering Locks 534wait() and notify() Methods 536Summary 546

    Chapter 16 Input and Output 551An Overview of the java.io Package 551

    The Output Streams 552The Input Stream Classes 553The Writer Class 553The Reader Class 554

    Low-Level and High-Level Streams 557Low-Level Streams 557High-Level Streams 559

    Chaining Streams Together 561Low-Level Readers and Writers 564High-Level Readers and Writers 564File I/O 565The RandomAccessFile Class 566Using Pipes 570An Overview of Serialization 574Serializing an Object 577Deserializing an Object 578The Logging APIs 579

    An Example of Logging 581Summary 587

    Chapter 17 Network Programming 591An Overview of Network Programming 591

    Transmission Control Protocol 592User Datagram Protocol 592

    Using Sockets 594The ServerSocket Class 596Socket Class 599Communicating between Sockets 600Java Secure Socket Extension (JSSE) 602Secure Server Socket 603Secure Client Socket 607Communicating over a Secure Socket 610Overview of Datagram Packets 612

    DatagramSocket Class 612DatagramPacket Class 613

    Contents xv

    b423149 FM.qxd 6/30/03 3:36 PM Page xv

  • Receiving a Datagram Packet 614Sending a Datagram Packet 615Working with URLs 617URL Connections 619Summary 625

    Chapter 18 Database Programming 629An Overview of JDBC 629JDBC Drivers 632Connecting to a Database 633

    Using the DriverManager Class 634Using the DataSource Class 636

    An SQL Primer 637Creating Data 638Reading Data 639Updating Data 640Deleting Data 641

    Creating Statements 641Simple Statements 642Working with Result Sets 647Navigating a Result Set 647Viewing a Result Set 648Updating a Result Set 651Prepared Statements 652

    Step 1: Preparing the Statement 652Step 2: Setting the Parameters 654Step 3: Executing a Prepared Statement 654

    Callable Statements 656Summary 663

    Chapter 19 JavaBeans 669Overview of JavaBeans 669Simple Properties 672Packaging a Bean 675

    Step 1: Write the Bean Class 676Step 2: Write the Manifest File 676Step 3: Create the JAR File 677Step 4: Download the Bean Builder 678Step 5: Run the Bean Builder 678Step 6: Load the Movie Bean into the Bean Builder 681Step 7: Using the Movie Bean in the Builder Tool 681

    Bound Properties 684Step 8: Binding Properties in the Bean Builder 687

    Constrained Properties 690Vetoing an Event 693

    xvi Contents

    b423149 FM.qxd 6/30/03 3:36 PM Page xvi

  • Overview of Events 694Step 9: Hooking up Buttons to the Movie Bean 695Step 10: Viewing Beans in Preview Mode 696

    Generating User-Defined Events 698BeanInfo Class 703Summary 708

    Appendix About the 60 Minutes Web Site 713

    Index 717

    Contents xvii

    b423149 FM.qxd 6/30/03 3:36 PM Page xvii

  • b423149 FM.qxd 6/30/03 3:36 PM Page xviii

  • I would like to thank the editors for their hard work on this book: J.W. (Jerry)Olsen, Nancy Sixsmith, and Susan Hobbs, and everyone at Wiley Publishingwho helped in this project, especially Ben Ryan. Thanks also to Donis Marshallfor the opportunity to write a book for the 60 Minutes a Day series as well as toJerry for managing the editors on behalf of Gearhead.

    And then there is everyone out there who played a role, whether small orlarge, in my writing of this book: Susan Raposa, javalicense.com, my Mom(who can read it now), and most importantly, Megan, Ryan, Katelyn, andEmma.

    And finally, to all of those who kept asking me when my book would bepublished: Leo and Linda Schaefbauer; Steve, Beth, Geoffrey, Nathan, andAurora Venteicher; Michael and Tammy Schaefbauer; David Schaefbauer;Betty Haefner; Mark, Margaret, Marie, Melissa, and Jay VanDerWerff; Michele,Gabe, and Seth Raposa; Allen, Denise, Joseph, Rechele, Kathalena, Kurstin,Joshua, and Kristina Raposa; Dave, Maryann, Daniel, Duke, Davey, Dylan,and Darby Knoll; and Barb and Steve Sachs.

    Acknowledgments

    xix

    b423149 FM.qxd 6/30/03 3:36 PM Page xix

  • b423149 FM.qxd 6/30/03 3:36 PM Page xx

  • Richard F. Raposa is a Java instructor for JLicense, Inc., a Java courseware andtraining firm based in Rapid City, SD. One of the first Sun Certified JavaInstructors, Rich has taught courses on Java, J2EE, XML, Web Services, C++,Visual C++/MFC, Win32 Internals, UML, and other object-oriented technolo-gies at companies around the country. He has developed courses on almostevery aspect of Java and the J2EE technologies.

    About the Author

    xxi

    b423149 FM.qxd 6/30/03 3:36 PM Page xxi

  • b423149 FM.qxd 6/30/03 3:36 PM Page xxii

  • An Overview of Java in 60 Minutes a Day

    I will never forget taking my first Java class at Sun Microsystems in Dallas,Texas, in May, 1998. I had heard the many promises about Java and how itwould revolutionize software development, but I was skeptical and arrogantas I sat in the back of the class anxious to make life hard on the instructor.

    At the time, I was programming and teaching C++, mostly Visual C++ andthe Microsoft Foundation Classes. For some reason, after I learned C++, I fig-ured that would be the last programming language I would ever need to learn.My boss, on the other hand, had different ideas, because I was slated tobecome a Sun Certified Java Instructor.

    Contrary to my expectations, I was blown away by Java! It was logical, pre-dictable, powerful, and simple (compared to C++). Sun had taken the best ofthe existing object-oriented programming languages and removed many ofthe idiosyncrasies and problem areas. And the best part: Java is platform inde-pendent! You write a program once, and it can be executed on different oper-ating systems and devices without your even having to recompile your code.

    I have been travelling the country teaching Java now for the last 5 years, andI still get excited about standing up in front of a classroom of students who areseeing Java for the first time. One of my goals was to capture that enthusiasmon the pages of this book. I want you to appreciate why Java has become oneof the most popular and widely used programming languages in softwaredevelopment today.

    Introduction

    xxiii

    b423149 FM.qxd 6/30/03 3:36 PM Page xxiii

  • xxiv Introduction

    How This Book Is Organized

    The goal of this book is for you to be able to study each chapter in one hour,like a student sitting through a one-hour lecture. After you finish a chapter,there are labs that solidify what you learned by having you write code. Youwill also find review questions and answers at the end of each chapter to helpyou review the key points of the chapter. Also throughout the book are Class-room Q&A sections where I answer questions that I have frequently beenasked by students in the classroom.

    The book contains 19 chapters. The first eight chapters discuss the funda-mentals of the Java language, and should be read in order. The order of the last11 chapters isn’t quite as important, although you will find that many of thelabs build on the ones from previous chapters. The following sections describewhat you will learn in this book’s chapters.

    Chapter 1: Getting Started with JavaIt just wouldn’t be a programming class if I didn’t start with the “Hello,World” application. In Chapter 1, you will learn what all the hype is aboutwith Java. I will discuss the life cycle of a Java program, then you will see howto write, compile, and execute a Java program using the Java 2 Platform, Stan-dard Edition (J2SE) Standard Developer Kit (SDK).

    Here’s a tip: If you have a slow Internet connection, you might want to startdownloading the J2SE SDK before you start reading the chapter.

    Chapter 2: Java FundamentalsThis chapter covers the fundamentals of Java, such as keywords, the built-indata types, strings, variables, references, and arithmetic operators. The infor-mation in this chapter establishes the foundation for the remainder of thebook, so take your time and make sure you understand everything.

    If you are a C or C++ programmer, don’t skip over this chapter thinking youalready know what’s in it. Java looks similar to C++, but it behaves quite dif-ferently.

    Chapter 3: Control StructuresIn this chapter, you will learn the various control structures in Java and thedetails of how to use them, including if/else, switch, do/while, and if state-ments. I will also cover Boolean operators and the truth tables.

    There are some fun labs in this chapter, including one where you write aprogram to simulate the Powerball lottery.

    b423149 FM.qxd 6/30/03 3:36 PM Page xxiv

  • Chapter 4: Classes and ObjectsIn my opinion, this is the most important chapter in the book, whether or notyou are new to object-oriented programming (OOP). Java is purely object-oriented, so to be a Java programmer is to understand classes and objects. In this chapter, you will learn how to think like an object-oriented programmer,as opposed to thinking procedurally. The basics of OOP are discussed: thatobjects consist of attributes and behaviors, and that classes describe objects. I will also briefly discuss the Unified Modeling Language (UML) and give youa taste of Object Oriented Analysis and Design (OOAD). The important topicof Java references is also covered in detail.

    Spend extra time on this chapter if you need to, because all of the topicsrequire your complete understanding before you can write Java programs.

    Chapter 5: MethodsThe behaviors of an object becomes methods in a class. By Chapter 5, you willbe familiar with writing classes, so it’s time to discuss all of the details aboutwriting and invoking Java methods. Topics covered in this chapter include themethod call stack, method signatures, parameters, arguments, method over-loading, constructors, and the always-important discussion of call-by-value inJava.

    The labs in this chapter give you the opportunity to really get a feel forobjects and OOP. You will write classes, instantiate objects, and invoke meth-ods on those objects.

    Chapter 6: Understanding InheritanceObject-oriented programming has four major aspects: inheritance, encapsula-tion, polymorphism, and abstraction. This chapter focuses on the most impor-tant of the four: inheritance. A new child class can be written that extends anexisting class, inheriting the attributes and behaviors of its parent. This chap-ter discusses when and how to use inheritance, including the “is a” relation-ship, the extends keyword, the Object class, method overriding, and a repeatdiscussion on constructors and how they are affected by inheritance.

    If I were to rank chapters in order of their importance, I would put this onesecond behind Chapter 4, “Classes and Objects.” An understanding of inheri-tance is essential to understanding the remaining chapters of the book.

    Chapter 7: Advanced Java Language ConceptsIn this chapter, I tie up some loose ends and discuss the details of some of themore advanced topics of Java. Topics covered in this chapter include packages,

    Introduction xxv

    b423149 FM.qxd 6/30/03 3:36 PM Page xxv

  • the access specifiers, encapsulation, static fields and methods, and the javadoctool.

    Some of these topics, such as packages and the javadoc tool, are of specialinterest because they are concepts unique to Java. I think javadoc is one of themost impressive features of the Java language, as you may also agree after yousee how it works.

    Chapter 8: Polymorphism and AbstractionPolymorphism is the capability of an object to take on different forms. Abstrac-tion refers to the use of abstract classes, classes that cannot be instantiated. Inthis chapter, I discuss the details of these two object-oriented concepts, includ-ing polymorphic parameters, heterogeneous collections, the instanceof key-word, virtual methods, and abstract methods.

    This is likely the most difficult chapter in the book. The concept of polymor-phism is crucial but difficult to explain, so I make an asserted effort to simplifymy discussions. Read this chapter carefully, and refer back to it whenever youneed to.

    Chapter 9: CollectionsAfter eight days of building a foundation for programming in Java, you willnow be ready to start using some of the many Java APIs that compose the Java2 Platform, Standard Edition (J2SE). Chapter 9 covers the classes in the JavaCollections API. If you have ever had to write code to create a linked list, hashtable, tree, or other data structure, you will be happy to find that the J2SE con-tains classes for all the commonly used data structures.

    This is a useful chapter for anyone, no matter what types of problems youwill be solving in your Java programming future.

    Chapter 10: InterfacesThe Java language contains the concept of interfaces, which allow you to cre-ate data types based on a set of behaviors. A class implements an interface,thereby causing the class to take on the data type of the interface. The classmust also implement the methods of the interface, which is how interfaces canbe used to force behavior on classes.

    This chapter covers the details of writing and implementing interfaces.Knowledge of interfaces is an absolute must in Java, so study this chapterclosely.

    xxvi Introduction

    b423149 FM.qxd 6/30/03 3:36 PM Page xxvi