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

java java java OOP solving

866 5 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

Cấu trúc

  • THE SOLUTION MANUAL

Nội dung

www.elsolucionario.net Java, Java, Java Object-Oriented Problem Solving Third Edition R Morelli and R Walde Trinity College Hartford, CT February 5, 2012 www.elsolucionario.net This work is licensed under a Creative Commons Attribution-NoDerivs 3.0 Unported License This book was previously published by Pearson Education, Inc www.elsolucionario.net Preface to the Open Source Edition Java, Java, Java, 3e was previously published by Pearson Education, Inc The first edition (2000) and the second edition (2003) were published by Prentice-Hall In 2010 Pearson Education, Inc reassigned the copyright to the authors, and we are happy now to be able to make the book available under an open source license This PDF edition of the book is available under a Creative Commons Attribution-NoDerivs 3.0 Unported License, which allows the book to be used and shared (with attribution), but not changed ( http://creativecommons.org/licenses/by-nd/3.0/) As time permits we hope to be able to provide an extensible version of the book and its contents in the not too distant future – Ralph Morelli and Ralph Walde – Hartford, CT – February 6, 2012 i www.elsolucionario.net ii www.elsolucionario.net Preface to the Third Edition We have designed this third edition of Java, Java, Java to be suitable for a typical Introduction to Computer Science (CS1) course or for a slightly more advanced Java as a Second Language course This edition retains the “objects first” approach to programming and problem solving that was characteristic of the first two editions Throughout the text we emphasize careful coverage of Java language features, introductory programming concepts, and object-oriented design principles The third edition retains many of the features of the first two editions, including: • Early Introduction of Objects • Emphasis on Object Oriented Design (OOD) • Unified Modeling Language (UML) Diagrams • Self-study Exercises with Answers • Programming, Debugging, and Design Tips • From the Java Library Sections • Object-Oriented Design Sections • End-of-Chapter Exercises • Companion Web Site, with Power Points and other Resources The In the Laboratory sections from the first two editions have been moved onto the book’s Companion Web Site Table shows the Table of Contents for the third edition What’s New in the Third Edition The third edition has the following substantive changes: • Although the book retains its emphasis on a “running example” that is revisited in several chapters, the CyberPet examples have been replaced with a collection of games and puzzle examples The CyberPet examples from earlier editions will be available on the Companion Web Site iii www.elsolucionario.net iv Chapter Chapter Chapter Chapter Chapter Chapter Chapter Chapter Chapter Chapter Chapter Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Table 1: Table of Contents for the Third Edition Topic Computers, Objects, and Java (revised) Java Program Design and Development Objects: Defining, Creating, and Using Methods: Communicating with Objects (revised) Input/Output: Designing the User Interface (new) Java Data and Operators Control Structures Strings and String Processing Inheritance and Polymorphism (new) Arrays and Array Processing Exceptions: When Things Go Wrong Files and Streams Recursive Problem Solving Graphical User Interfaces Threads and Concurrent Programming Sockets and Networking (expanded) Data Structures: Lists, Stacks, and Queues (revised and expanded) • Chapters (Computers, Objects, and Java) and (Java Program Design and Development) have been substantially reorganized and rewritten The new presentation is designed to reduce the pace with which new concepts are introduced The treatment of objectoriented (OO) and UML concepts has also been simplified, and some of the more challenging OO topics, such as polymorphism, have been moved to a new Chapter • The new Java 1.5 Scanner class is introduced in Chapter and is used to perform simple input operations • Chapter (Input/Output: Designing the User Interface) has been completely written Rather than relying primarily on applet interfaces, as in the second edition, this new chapter provides independent introductions to both a command-line interface and a graphical user interface (GUI) Instructors can choose the type of interface that best suits their teaching style The command-line interface is based on the BufferedReader class and is used throughout the rest of the text The GUI is designed to work with either graphical applications or applets Both approaches are carefully presented to highlight the fundamentals of user-interface design The chapter concludes with an optional section that introduces file I/O using the new Scanner class • Much of the discussion of inheritance and polymorphism, which was previously woven through the first five chapters in the second edition, has been integrated into a new Chapter • An optional graphics track is woven throughout the text Beginning with simple examples in Chapters and 2, this track also includes www.elsolucionario.net v some of the examples that were previously presented in Chapter 10 of the second edition • Chapter 15, on Sockets and Networking, is expanded to cover some of the more advanced Java technologies that have emerged, including servlets and Java Server Pages • Chapter 16, on Data Structures, has been refocused on how to use data structures It makes greater use of Java’s Collection Framework, including the LinkedList and Stack classes and the List interface It has been expanded to cover some advanced data structures, such as sets, maps, and binary search trees The Essentials Edition An Essentials Edition of the third edition, which will include Chapters 012, will be published as a separate title The Essentials Edition will cover those topics (Chapters 0-9) that are covered in almost all introductory (CS1) courses, but it will also include topics (Exceptions, File I/O, and Recursion) that many CS1 instructors have requested Why Start with Objects? The Third Edition still takes an objects-early approach to teaching Java, with the assumption that teaching beginners the “big picture” early gives them more time to master the principles of object-oriented programming This approach seems now to have gained in popularity as more and more instructors have begun to appreciate the advantages of the object-oriented perspective Object Orientation (OO) is a fundamental problem solving and design concept, not just another language detail that should be relegated to the middle or the end of the book (or course) If OO concepts are introduced late, it is much too easy to skip over them when push comes to shove in the course The first time I taught Java in our CS1 course I followed the same approach I had been taking in teaching C and C++ — namely, start with the basic language features and structured programming concepts and then, somewhere around midterm, introduce object orientation This approach was familiar, for it was one taken in most of the textbooks then available in both Java and C++ One problem with this approach was that many students failed to get the big picture They could understand loops, if-else constructs, and arithmetic expressions, but they had difficulty decomposing a programming problem into a well-organized Java program Also, it seemed that this procedural approach failed to take advantage of the strengths of Java’s object orientation Why teach an object-oriented language if you’re going to treat it like C or Pascal? I was reminded of a similar situation that existed when Pascal was the predominant CS1 language Back then the main hurdle for beginners was procedural abstraction — learning the basic mechanisms of procedure call www.elsolucionario.net vi and parameter passing and learning how to design programs as a collection of procedures Oh! Pascal!, my favorite introductory text, was typical of a “procedures early” approach It covered procedures and parameters in Chapter 2, right after covering the assignment and I/O constructs in Chapter It then covered program design and organization in Chapter It didn’t get into loops, if-else, and other structured programming concepts until Chapter and beyond Today, the main hurdle for beginners is the concept of object abstraction Beginning programmers must be able to see a program as a collection of interacting objects and must learn how to decompose programming problems into well-designed objects Object orientation subsumes both procedural abstraction and structured programming concepts from the Pascal days Teaching objects-early takes a top-down approach to these three important concepts The sooner you begin to introduce objects and classes, the better the chances that students will master the important principles of object orientation Java is a good language for introducing object orientation Its object model is better organized than C++ In C++ it is easy to “work around” or completely ignore OO features and treat the language like C In Java there are good opportunities for motivating the discussion of object orientation For example, it’s almost impossible to discuss GUI-based Java applications without discussing inheritance and polymorphism Thus rather than using contrived examples of OO concepts, instructors can use some of Java’s basic features — the class library, Swing and GUI components — to motivate these discussions in a natural way Organization of the Text The book is still organized into three main parts Part I (Chapters 0-4) introduces the basic concepts of object orientation and the basic features of the Java language Part II (Chapters 5-9) focuses on remaining language elements, including data types, control structures, string and array processing, and inheritance and polymorphism Part III (Chapters 10-16) covers advanced topics, including exceptions, file I/O, recursion, GUIs, threads and concurrent programming, sockets and networking, data structures, servlets, and Java Server Pages The first two parts make up the topics that are typically covered in an introductory CS1 course The chapters in Part III are self-contained and can be selectively added to the end of a CS1 course if time permits The first part (Chapters through 4) introduces the basic concepts of object orientation, including objects, classes, methods, parameter passing, information hiding, and a little taste of inheritance, and polymorphism The primary focus in these chapters is on introducing the basic idea that an object-oriented program is a collection of objects that communicate and cooperate with each other to solve problems Java language elements are introduced as needed to reinforce this idea Students are given the basic building blocks for constructing Java programs from scratch Although the programs in the first few chapters have limited functionality in terms of control structures and data types, the priority is placed www.elsolucionario.net vii Weeks 2-3 6–7 10 11 12 13 Table 2: A one-semester course Topics Object Orientation, UML Program Design and Development Objects and Class Definitions Methods and Parameters Selection structure (if-else) User Interfaces and I/O Data Types and Operators Control Structures (Loops) Structured Programming String Processing (loops) Inheritance and Polymorphism Array Processing Recursion Advanced Topic (Exceptions) Advanced Topic (GUIs) Advanced Topic (Threads) Chapters Chapter Chapter Chapter Chapter Chapter Chapter Chapter Chapter Chapter Chapter Chapter 12 Chapter 10 Chapter 11 Chapter 15 on how objects are constructed and how they interact with each other through method calls and parameter passing The second part (Chapters through 9) focuses on the remaining language elements, including data types and operators (Chapter 5), control structures (Chapter 6), strings (Chapter 7), and arrays (Chapter 9) It also provides thorough coverage of inheritance and polymorphism, the primary mechanisms of object orientation: (Chapter 8) Part three (Chapters 10 through 16) covers a variety of advanced topics (Table 1) Topics from these chapters can be used selectively depending on instructor and student interest Throughout the book, key concepts are introduced through simple, easy-to-grasp examples Many of the concepts are used to create a set of games, which are used as a running example throughout the text Our pedagogical approach focuses on design Rather than starting of with language details, programming examples are carefully developed with an emphasis on the principles of object-oriented design Table2 provides an example syllabus from our one-semester CS1 course Our semester is 13 weeks (plus one reading week during which classes not meet) We pick and choose from among the advanced topics during the last two weeks of the course, depending on the interests and skill levels of the students Ralph Morelli February 5, 2012 www.elsolucionario.net Appendix E Operator Precedence Hierarchy Table E.1 summarizes the precedence and associativity relationships for Java operators Within a single expression, an operator of order m would be evaluated before an operator of order n if m < n Operators having the same order are evaluated according to their association order For example, the expression ☛ ✟ 25 + ∗ + ✡ ✠ would be evaluated in the order shown by the following parenthesized expression: ☛ (25 + (5 ∗ ) ) + ✟ ==> ( + ) + ==> 35 + ==> 38 ✡ ✠ In other words, because * has higher precedence than +, the multiplication operation is done before either of the addition operations And because addition associates from left to right, addition operations are performed from left to right Most operators associate from left to right, but note that assignment operators associate from right to left For example, consider the following code segment: ☛ int i , j , k ; i = j = k = 100; ✟ // Equivalent to i = ( j = (k = 100)); ✡ ✠ In this case, each variable will be assigned 100 as its value But it’s important that this expression be evaluated from right to left First, k is assigned 100 Then its value is assigned to j And finally j’s value is assigned to i For expressions containing mixed operators, it’s always a good idea to use parentheses to clarify the order of evaluation This will also help avoid subtle syntax and semantic errors 835 www.elsolucionario.net APPENDIX E • Operator Precedence Hierarchy 836 TABLE E.1 Java operator precedence and associativity table Order Operator Operation ( ) ++ · ++ + 10 11 (type) new * / % + - + < > = == != ∧ && —— = += -= *= /= %= Parentheses Postincrement, Postdecrement, Dot Operator Preincrement, Predecrement, Unary plus, Unary minus, Boolean NOT Type Cast, Object Instantiation Multiplication, Division, Modulus Addition, Subtraction, String Concatenation Relational Operators Equality Operators Boolean XOR Boolean AND Boolean OR Assignment Operators - ! Association L to R R to L R to L L to R L to R L to R L to R L to R L to R L to R R to L www.elsolucionario.net Appendix F Java Inner Classes This appendix describes basic features of some advanced elements of the Java language As for many language features, there are details and subtleties involved in using these features that are not covered here For further details, you should consult Sun’s online references or other references for a more comprehensive description What Are Inner Classes? Inner classes were introduced in Java 1.1 This features lets you define a class as part of another class, just as fields and methods are defined within classes Inner classes can be used to support the work of the class in which they are contained Java defines four types of inner classes A nested top-level class or interface is a static member of an enclosing top-level class or interface Such classes are considered top-level classes by Java A member class is a nonstatic inner class It is not a top-level class As a fullfledged member of its containing class, a member class can refer to the fields and methods of the containing class, even the private fields and methods Just as you would expect for the other instance fields and methods of a class, all instances of a member class are associated with an instance of the enclosing class A local class is an inner class that’s defined within a block of Java code, such as within a method or within the body of a loop Local classes have local scope—they can only be used within the block in which they are defined Local classes can refer to the methods and variables of their enclosing classes They are used mostly to implement adapters, which are used to handle events When Java compiles a file containing a named inner class, it creates separate class files for them with names that include the nesting class as a qualifier For example, if you define an inner class named Metric inside a toplevel class named Converter, the compiler will create a class file named Converter$Metric.class for the inner class If you wanted to access the inner class from some other class (besides Converter), you would use a qualified name: Converter.Metric An anonymous class is a local class whose definition and use are combined into a single expression Rather than defining the class in one statement and using it in another, both operations are combined into a single expression Anonymous classes are intended for one-time use Therefore, they don’t contain constructors Their bytecode files are given names like ConverterFrame$1.class 837 www.elsolucionario.net APPENDIX F • Java Inner Classes 838 Nested Top-Level Versus Member Classes The Converter class (Figure F–1) shows the differences between a nested toplevel class and a member class The program is a somewhat contrived example that performs various kinds of metric conversions The outer Converter class ☛ ✟ public c l a s s Converter { p r i v a t e s t a t i c f i n a l double INCH PER METER = ; p r i v a t e f i n a l double LBS PER KG = ; public s t a t i c c l a s s D i s t a n c e { / / N e s t e d T o p − l e v e l public double metersToInches ( double meters ) { r e t u r n meters ∗ INCH PER METER ; } } // D i s t a n c e public c l a s s Weight { // Member public double kgsToPounds ( double kg ) { r e t u r n kg ∗ LBS PER KG ; } } // W e i g h t } class class // C o n v e r t e r public c l a s s ConverterUser { public s t a t i c void main ( S t r i n g a r g s [ ] ) { Converter D i s t a n c e d i s t a n c e = new Converter D i s t a n c e ( ) ; Converter c o n v e r t e r = new Converter ( ) ; Converter Weight weight = c o n v e r t e r new Weight ( ) ; System out p r i n t l n ( ” m = ” + d i s t a n c e metersToInches ( ) + ” i n ” ) ; System out p r i n t l n ( ” kg = ” + weight kgsToPounds ( ) + ” l b s ” ) ; } } // C o n v e r t e r U s e r ✡ ✠ Figure F–1: A Java application containing a top-level nested class serves as a container for the inner classes, Distance and Weight, which perform specific conversions The Distance class is declared static, so it is a top-level class It is contained in the Converter class itself Note the syntax used in ConverterUser.main() to create an instance of the Distance class: ☛ ✟ Converter D i s t a n c e d i s t a n c e = new Converter D i s t a n c e ( ) ; ✡ ✠ A fully qualified name is used to refer to the static inner class via its containing class The Weight class is not declared static It is, therefore, associated with instances of the Converter class Note the syntax used to create an instance of the Weight class: ☛ ✟ Converter c o n v e r t e r = new Converter ( ) ; Converter Weight weight = c o n v e r t e r new Weight ( ) ; ✡ ✠ www.elsolucionario.net APPENDIX F • Java Inner Classes 839 Before you can create an instance of Weight, you have to declare an instance of Converter In this example, we have used two statements to create the weight object, which requires using the temporary variable, converter, as a reference to the Converter object We could also have done this with a single statement by using the following syntax: ☛ ✟ Converter Weight weight = new Converter ( ) new Weight ( ) ; ✡ ✠ Note that in either case the qualified name Converter.Weight must be used to access the inner class from the ConverterUser class There are a couple of other noteworthy features in this example First, an inner top-level class is really just a programming convenience It behaves just like any other top-level class in Java One restriction on top-level inner classes is that they can only be contained within other top-level classes, although they can be nested one within the other For example, we could nest additional converter classes within the Distance class Java provides special syntax for referring to such nested classes Unlike a top-level class, a member class is nested within an instance of its containing class Because of this, it can refer to instance variables (LBS_PER_KG) and instance methods of its containing class, even to those declared private By contrast, a top-level inner class can only refer to class variables (INCH_PER_METER)— that is, to variables that are declared static So you would use a member class if it were necessary to refer to instances of the containing class There are many other subtle points associated with member classes, including special language syntax that can be used to refer to nested member classes and rules that govern inheritance and scope of member classes For these details you should consult the Java Language Specification, which can be accessed online at ☛ ✟ h t t p : // j a v a sun com/docs/books/ j l s /html/index html ✡ Local and Anonymous Inner Classes In this next example, ConverterFrame, a local class is used to create an ActionEvent handler for the application’s two buttons (Fig F–2) As we have seen, Java’s event-handling model uses predefined interfaces, such as the ActionListener interface, to handle events When a separate class is defined to implement an interface, it is sometimes called an adapter class Rather than defining adapter classes as top-level classes, it is often more convenient to define them as local or anonymous classes The key feature of the ConverterFrame program is the createJButton() method This method is used instead of the JButton() constructor to create buttons and to create action listeners for the buttons It takes a single String parameter for the button’s label It begins by instantiating a new JButton, a reference to which is passed back as the method’s return value After creating an instance button, a local inner class named ButtonListener is defined The local class merely implements the ActionListener interface by defining the actionPerformed method Note how actionPerformed() uses the containing class’s converter variable to acquire access to the metersToInches() and kgsToPounds() methods, which are inner class methods of the Converter class (Fig F–1) A local class can use instance variables, such as converter, that are defined in its containing class After defining the local inner class, the createJButton() method creates an instance of the class (listener) and registers it as the button’s action listener ✠ www.elsolucionario.net 840 ☛ APPENDIX F • Java Inner Classes ✟ import j a v a x swing ∗ ; import j a v a awt ∗ ; import j a v a awt event ∗ ; public c l a s s ConverterFrame extends JFrame { p r i v a t e Converter c o n v e r t e r = new Converter ( ) ; p r i v a t e J T e x t F i e l d i n F i e l d = new J T e x t F i e l d ( ) ; p r i v a t e J T e x t F i e l d o u t F i e l d = new J T e x t F i e l d ( ) ; p r i v a t e J B u t t o n metersToInch ; p r i v a t e J B u t t o n kgsToLbs ; // Reference to app public ConverterFrame ( ) { metersToInch = c r e a t e J B u t t o n ( ” Meters To I n c h e s ” ) ; kgsToLbs = c r e a t e J B u t t o n ( ” K i l o s To Pounds” ) ; getContentPane ( ) s e t L a y o u t ( new FlowLayout ( ) ) ; getContentPane ( ) add ( i n F i e l d ) ; getContentPane ( ) add ( o u t F i e l d ) ; getContentPane ( ) add ( metersToInch ) ; getContentPane ( ) add ( kgsToLbs ) ; } // C o n v e r t e r F r a m ( ) p r i v a t e JButton c r e a t e J B u t t o n ( S t r i n g s ) { // A m e t h o d J B u t t o n j b u t t o n = new J B u t t o n ( s ) ; c l a s s B u t t o n L i s t e n e r implements A c t i o n L i s t e n e r { / / to create Local a JButton class public void actionPerformed ( ActionEvent e ) { double inValue = Double valueOf ( i n F i e l d g e t T e x t ( ) ) doubleValue ( ) ; J B u t t o n button = ( J B u t t o n ) e g e t S o u r c e ( ) ; i f ( button g e t T e x t ( ) e q u a l s ( ” Meters To I n c h e s ” ) ) o u t F i e l d s e t T e x t ( ” ”+ c o n v e r t e r new D i s t a n c e ( ) metersToInches ( inValue ) ) ; else o u t F i e l d s e t T e x t ( ” ”+ c o n v e r t e r new Weight ( ) kgsToPounds ( inValue ) ) ; } // a c t i o n P e r f o r m e d ( ) } // ButtonListener A c t i o n L i s t e n e r l i s t e n e r = new B u t t o n L i s t e n e r ( ) ; / / C r e a t e a l i s t e n e r jbutton addActionListener ( l i s t e n e r ) ; // R e g i s t e r b u t t o n s w i t h l i s t e n e r return jbutton ; } // createJButton () public s t a t i c void main ( S t r i n g a r g s [ ] ) { ConverterFrame frame = new ConverterFrame ( ) ; frame s e t S i z e ( 0 , 0 ) ; frame s e t V i s i b l e ( t r u e ) ; } // m a i n ( ) } // ConverterFrame ✡ ✠ Figure F–2: The use of a local class as an ActionListener adapter When a separate object is created to serve as listener in this way, it is called an adapter It implements a listener interface and thereby serves as adapter between the event and the object that generated the event Any action events that occur on any buttons created with this method will be handled by this adapter In other www.elsolucionario.net APPENDIX F • Java Inner Classes 841 words, for any buttons created by the createJButton() method, a listener object is created and assigned as the button’s event listener By using local classes, the code for doing this is much more compact and efficient Local classes have some important restrictions Although an instance of a local class can use fields and methods defined within the class itself or inherited from its superclasses, it cannot use local variables and parameters defined within its scope unless these are declared final The reason for this restriction is that final variables receive special handling by the Java compiler Because the compiler knows that the variable’s value won’t change, it can replace uses of the variable with their values at compile time www.elsolucionario.net APPENDIX F • Java Inner Classes 842 Anonymous Inner Classes An anonymous inner class is just a local class without a name Instead of using two separate statements to define and instantiate the local class, Java provides syntax that let’s you it in one expression The following code illustrates how this is done: ☛ ✟ private JButton createJButton ( String s ) { J B u t t o n j b u t t o n = new J B u t t o n ( s ) ; // A m e t h o d to create a JButton j b u t t o n a d d A c t i o n L i s t e n e r ( new A c t i o n L i s t e n e r ( ) { // A n o n y m o u s c l a s s public void actionPerformed ( ActionEvent e ) { double inValue = Double valueOf ( i n F i e l d g e t T e x t ( ) ) doubleValue ( ) ; J B u t t o n button = ( J B u t t o n ) e g e t S o u r c e ( ) ; i f ( button g e t L a b e l ( ) e q u a l s ( ” Meters To I n c h e s ” ) ) o u t F i e l d s e t T e x t ( ” ” + c o n v e r t e r new D i s t a n c e ( ) metersToInches ( inValue ) ) ; else o u t F i e l d s e t T e x t ( ” ” + c o n v e r t e r new Weight ( ) kgsToPounds ( inValue ) ) ; } // a c t i o n P e r f o r m e d ( ) } ) ; // A c t i o n L i s t e n e r return jbutton ; } // createJButton () ✡ ✠ Note that the body of the class definition is put right after the new operator The result is that we still create an instance of the adapter object, but we define it on the fly If the name following new is a class name, Java will define the anonymous class as a subclass of the named class If the name following new is an interface, the anonymous class will implement the interface In this example, the anonymous class is an implementation of the ActionListener interface Local and anonymous classes provide an elegant and convenient way to implement adapter classes that are intended to be used once and have relatively short and simple implementations The choice of local versus anonymous should largely depend on whether you need more than one instance of the class If so, or if it’s important that the class have a name for some other reason (readability), then you should use a local class Otherwise, use an anonymous class As in all design decisions of this nature, you should use whichever approach or style makes your code more readable and more understandable www.elsolucionario.net Appendix G Java Autoboxing and Enumeration This appendix describes some basic properties of autoboxing and enumeration, two of the features added to the Java language with the release of Java 5.0 As for many language features, there are details and subtleties involved in using these features that are not covered here For further details, you should consult Sun’s online references or other references for a more comprehensive description Autoboxing and Unboxing Autoboxing refers to the automatic storing of a value of primitive type into an object of the corresponding wrapper class Before autoboxing, it was necessary to explicitly box values into wrapper class objects with code like: ☛ ✟ I n t e g e r i O b j = new I n t e g e r ( ) ; double num = − ; Double dObj = new Double (num ) ; ✡ ✠ Java 5.0 automatically creates a wrapper class object from a value of primitive type in many situations where a wrapper class object is expected The assignments above can be accomplished with the simpler code: ☛ ✟ Integer iObj = 345; double num = − ; Double dObj = num ; ✡ ✠ There is a corresponding feature in Java 5.0 which automatically performs the unboxing of primitive values from wrapper class objects Instead of the explicit unboxing in: ☛ ✟ int m = iObj intValue ( ) ; double x = dObj doubleValue ( ) ; ✡ ✠ 843 www.elsolucionario.net 844 APPENDIX G • Java Autoboxing and Enumeration Java 5.0 allows the simpler: ☛ ✟ int m = iObj ; double x = dObj ; ✡ ✠ Java 5.0 provides autoboxing of primitive values and automatic unboxing of wrapper class objects in expressions or in arguments of methods, where such a conversion is needed to complete a computation Beginning programmers are unlikely to encounter many problems that require such conversions One situation which often requires boxing and unboxing are applications that involve data structures The generic type data structures of Chapter 16 must store objects but the data to be stored might be represented as values of a primitive type The code segment below should give you some idea of the type of situation where autoboxing and unboxing can be a genuine help simplifying one’s code: ☛ ✟ Stack s t a c k = new Stack ( ) ; f o r ( i n t k = −1; k > −5; k−−) s t a c k push ( k ) ; while ( ! s t a c k empty ( ) ) System out p r i n t l n ( Math abs ( s t a c k pop ( ) ) ) ; ✡ ✠ Notice that the stack.push(k) method is expecting an Integer object so the int value stored in k will be autoboxed into such an object before the method is executed Also note that the Math.abs() method in the last line of the code fragment is expecting a value of primitive type so the Integer value returned by stack.pop() must be automatically unboxed before the Math.abs() method can be applied Sun’s online Java 5.0 documentation can be consulted for a more precise description of where autoboxing and unboxing takes place and a list of some special situations where code allowing autoboxing can lead to confusion and problems Enumeration A new enumeration construct was included in Java 5.0 to make it simpler to represent a finite list of named values as a type The enum keyword was added as part of this construct Standard examples of lists of values appropriate for enumerations are the days of the week, months of the year, the four seasons, the planets, the four suits in a deck of cards, and the ranks of cards in a deck of cards The following declaration of Season enumerated type is an example used by the Sun online documentation ☛ ✟ public enum Season { spring , summer , f a l l , winter } ✡ Compiling a file that contains only this statement will create a Season.class file that defines a Java type just in the same way that compiling class definitions does The variables and values of type Season can be referred to in other classes ✠ www.elsolucionario.net APPENDIX G • Java Autoboxing and Enumeration 845 just like other types and values For example, the following statements are valid statements in a method definition in another class: ☛ ✟ Season s1 = winter ; i f ( s1 == s p r i n g ) System out p r i n t l n ( s1 ) ; ✡ ✠ Note that the values of enumerated types can be used in assignment statements, equality relations, and it will be printed out exactly as declared in the enum statement The enum declaration could also occur inside the definition of a class and be declared as either public or private In this case the visibility of the type would be determined in a manner similar to inner classes A standard way to represent such a finite list of values in Java before the enum construct was to create a list of constants of type int For example, if one wanted to represent the four seasons you would have to it inside a definition of a class, say of a class named Calendar Such a representation might look like: ☛ ✟ public c l a s s Calendar { public s t a t i c f i n a l public s t a t i c f i n a l public s t a t i c f i n a l public s t a t i c f i n a l // } // Other Calendar int int int int SPRING SUMMER FALL = WINTER = 0; = 1; 2; = 3; definitions Calendar ✡ ✠ In addition to being a lengthier declaration, note that other classes that wish to refer to this representation would have to use notation something like: ☛ ✟ i n t s1 = Calendar WINTER ; i f ( s1 == Calendar SPRING ) System out p r i n t l n ( s1 ) ; ✡ In addition to being more awkward, note that the println() call will print out an integer in this case Some additional code would have to be written to be able to print the names of the seasons from the int values used to represent them It is the case that for methods in the Calendar class, the names of the constants look very much like the values of the enum type ✠ www.elsolucionario.net APPENDIX G • Java Autoboxing and Enumeration 846 To illustrate a couple of additional advantages of the enum structure, lets consider using the int representation above in a method definition that describes the start date of a given season Code for such a method would look something like: ☛ ✟ public s t a t i c S t r i n g s t a r t D a t e ( i n t s ) { switch ( s ) { c a s e SPRING : r e t u r n ” Vernal Equinox ” ; c a s e SUMMER : r e t u r n ”Summer S o l s t i c e ” ; c a s e FALL : r e t u r n ”Autumnal Equinox ” ; c a s e WINTER : r e t u r n ” Winter S o l s t i c e ” ; } // s w i t c h return ” error ” ; } // s t a r t D a t e ( ) ✡ ✠ This method has a problem referred to as not being typesafe We would want the startDate() method to be called only with an argument equal to an int value of 0, 1, 2, or There is no way to tell the compiler to make sure that other int values are not used as an argument to this method Let’s contrast this with a similar startDate() method that can refer to the Season enumerated type that was defined above The Calendar class (Figure G– 1) shows the definition of a startDate() method as well as a method to print a list of seasons with corresponding starting dates Note that the parameter of ☛ ✟ public c l a s s Calendar { public s t a t i c S t r i n g s t a r t D a t e ( Season s ) { switch ( s ) { c a s e s p r i n g : r e t u r n ” Vernal Equinox ” ; c a s e summer : r e t u r n ”Summer S o l s t i c e ” ; c a s e f a l l : r e t u r n ”Autumnal Equinox ” ; c a s e winter : r e t u r n ” Winter S o l s t i c e ” ; } // s w i t c h return ” error ” ; } // s t a r t D a t e ( ) public s t a t i c void p r i n t D a t e s ( ) { f o r ( Season s : Season v a l u e s ( ) ) System out p r i n t l n ( s + ” − ” + s t a r t D a t e ( s ) ) ; } // p r i n t D a t e s ( ) } // Calendar ✡ ✠ Figure G–1: A Calendar class using the Season startDate() is of type Season and so the Java compiler can check that call to this method have an argument of this type This time the startDate() is typesafe The printDates() method illustrates another feature of the enumeration structure The for loop in this method is the for-in loop which was added to Java 5.0 The expression Season.values() denotes a list of the elements of the type in the order that they were declared The for-in loop iterates through all the values of the type in the correct order and, in this case, prints out the type www.elsolucionario.net APPENDIX G • Java Autoboxing and Enumeration 847 name followed by a dash followed by the String computed by the startDate() method The output when the printDates() method is called is given below: ☛ spring summer fall − winter ✟ − Vernal − Summer Autumnal − Winter Equinox Solstice Equinox Solstice ✡ The for-in loop provides a very nice way to iterate through the values of any enumerated type You may wish to write a corresponding method for the earlier int representation of the seasons for a comparison Sun’s online Java 5.0 documentation provides a more precise definition of enumerated types and describes quite a number of other features that we have not alluded to ✠ www.elsolucionario.net 848 APPENDIX G • Java Autoboxing and Enumeration www.elsolucionario.net Appendix H Java and UML Resources Reference Books • David Flanagan, Java in a Nutshell Edition 5, 5th ed., O’Reilly and Associates 2005 Part of the O’Reilly Java series, this book provides a concise desktop reference to Java and the API • James Gosling, Bill Joy, and Guy Steele, The Java Language Specification, 3d ed., Addison-Wesley, 2005 This book, which is part of Addison-Wesley’s Java Series, provides a detailed description of the Java language An online version is available at ☛ ✟ h t t p : // j a v a sun com/docs/books/ j l s ✡ ✠ • Martin Fowler, UML Distilled, 3d ed., Addison-Wesley, 2003 This book, which is part of Addison-Wesley’s Object Technology Series, provides a concise introduction to UML Online References • http://www.omg.org/ contains good information on UML • http://java.sun.com/j2se is one of Sun Microsystems’ Java Web sites From this page you can find links to downloads of JDK, API specifications, and documentation on all of Java, including Swing, AWT, and new features of Java 5.0 • http://java.sun.com/docs/codeconv/ provides a description of coding conventions suggested by the Java Language Specification and followed by the Java programming community (These are summarized in Appendix A.) • http://java.sun.com/tutorial provides an online Java tutorial • http://www.JARS.com provides reviews and ratings of the best Java applets • http://www.java-news-center.org/ is a clearinghouse for Java news, programming examples, debugging tips, and many other useful resources 849 ... The Java Development Kit 821 C The ASCII and Unicode Character Sets 831 D Java Keywords 833 E Operator Precedence Hierarchy 835 F Java Inner Classes 837 G Java Autoboxing and Enumeration 843 H Java. .. 0.6 0.7 Why Java? What Is Object-Oriented Programming? Chapter Summary Exercises www.elsolucionario.net CHAPTER • Computers, Objects, and Java 0.1 Welcome Welcome to Java, Java, Java, a book... have designed this third edition of Java, Java, Java to be suitable for a typical Introduction to Computer Science (CS1) course or for a slightly more advanced Java as a Second Language course This

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

w