Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Chapter 7 Arrays Arrays • Arrays are objects that help us organize large amounts of information • Chapter 7 focuses on: array declaration and use bounds checking and capacity arrays that store object references variable length parameter lists multidimensional arrays the ArrayList class polygons and polylines mouse events and keyboard events © 2004 Pearson Addison-Wesley. All rights reserved 7-2 Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events © 2004 Pearson Addison-Wesley. All rights reserved 7-3 Arrays • An array is an ordered list of values Each value has a numeric index The entire array has a single name 0 scores 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91 An array of size N is indexed from zero to N-1 This array holds 10 values that are indexed from 0 to 9 © 2004 Pearson Addison-Wesley. All rights reserved 7-4 Arrays • A particular value in an array is referenced using the array name followed by the index in brackets • For example, the expression scores[2] refers to the value 94 (the 3rd value in the array) • That expression represents a place to store a single integer and can be used wherever an integer variable can be used © 2004 Pearson Addison-Wesley. All rights reserved 7-5 Arrays • For example, an array element can be assigned a value, printed, or used in a calculation: scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; System.out.println ("Top = " + scores[5]); © 2004 Pearson Addison-Wesley. All rights reserved 7-6 Arrays • The values held in an array are called array elements • An array stores multiple values of the same type – the element type • The element type can be a primitive type or an object reference • Therefore, we can create an array of integers, an array of characters, an array of String objects, an array of Coin objects, etc. • In Java, the array itself is an object that must be instantiated © 2004 Pearson Addison-Wesley. All rights reserved 7-7 Arrays • Another way to depict the scores array: scores © 2004 Pearson Addison-Wesley. All rights reserved 79 87 94 82 67 98 87 81 74 91 7-8 Declaring Arrays • The scores array could be declared as follows: int[] scores = new int[10]; • The type of the variable scores is int[] (an array of integers) • Note that the array type does not specify its size, but each object of that type has a specific size • The reference variable scores is set to a new array object that can hold 10 integers © 2004 Pearson Addison-Wesley. All rights reserved 7-9 Declaring Arrays • Some other examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; © 2004 Pearson Addison-Wesley. All rights reserved 7-10 Using Arrays • The iterator version of the for loop can be used when processing array elements for (int score : scores) System.out.println (score); • This is only appropriate when processing all array elements from top (lowest index) to bottom (highest index) • See BasicArray.java (page 372) © 2004 Pearson Addison-Wesley. All rights reserved 7-11 Bounds Checking • Once an array is created, it has a fixed size • An index used in an array reference must specify a valid element • That is, the index value must be in range 0 to N-1 • The Java interpreter throws an ArrayIndexOutOfBoundsException if an array index is out of bounds • This is called automatic bounds checking © 2004 Pearson Addison-Wesley. All rights reserved 7-12 Bounds Checking • For example, if the array codes can hold 100 values, it can be indexed using only the numbers 0 to 99 • If the value of count is 100, then the following reference will cause an exception to be thrown: System.out.println (codes[count]); • It’s common to introduce off-by-one errors when using arrays problem for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon; © 2004 Pearson Addison-Wesley. All rights reserved 7-13 Bounds Checking • Each array object has a public constant called length that stores the size of the array • It is referenced using the array name: scores.length • Note that length holds the number of elements, not the largest index • See ReverseOrder.java (page 375) • See LetterCount.java (page 376) © 2004 Pearson Addison-Wesley. All rights reserved 7-14 Alternate Array Syntax • The brackets of the array type can be associated with the element type or with the name of the array • Therefore the following two declarations are equivalent: float[] prices; float prices[]; • The first format generally is more readable and should be used © 2004 Pearson Addison-Wesley. All rights reserved 7-15 Initializer Lists • An initializer list can be used to instantiate and fill an array in one step • The values are delimited by braces and separated by commas • Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', ’F'}; © 2004 Pearson Addison-Wesley. All rights reserved 7-16 Initializer Lists • Note that when an initializer list is used: the new operator is not used no size value is specified • The size of the array is determined by the number of items in the initializer list • An initializer list can be used only in the array declaration • See Primes.java (page 381) © 2004 Pearson Addison-Wesley. All rights reserved 7-17 Arrays as Parameters • An entire array can be passed as a parameter to a method • Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other • Therefore, changing an array element within the method changes the original • An individual array element can be passed to a method as well, in which case the type of the formal parameter is the same as the element type © 2004 Pearson Addison-Wesley. All rights reserved 7-18 Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events © 2004 Pearson Addison-Wesley. All rights reserved 7-19 Arrays of Objects • The elements of an array can be object references • The following declaration reserves space to store 5 references to String objects String[] words = new String[5]; • It does NOT create the String objects themselves • Initially an array of objects holds null references • Each object stored in an array must be instantiated separately © 2004 Pearson Addison-Wesley. All rights reserved 7-20 Arrays of Objects • The words array when initially declared: words - • At this point, the following reference would throw a NullPointerException: System.out.println (words[0]); © 2004 Pearson Addison-Wesley. All rights reserved 7-21 Arrays of Objects • After some String objects are created and stored in the array: “friendship” words “loyalty” “honor” - © 2004 Pearson Addison-Wesley. All rights reserved 7-22 Arrays of Objects • Keep in mind that String objects can be created using literals • The following declaration creates an array object called verbs and fills it with four String objects created using string literals String[] verbs = {"play", "work", "eat", "sleep"}; © 2004 Pearson Addison-Wesley. All rights reserved 7-23 Arrays of Objects • The following example creates an array of Grade objects, each with a string representation and a numeric lower bound • See GradeRange.java (page 384) • See Grade.java (page 385) • Now let's look at an example that manages a collection of CD objects • See Tunes.java (page 387) • See CDCollection.java (page 388) • See CD.java (page 391) © 2004 Pearson Addison-Wesley. All rights reserved 7-24 Arrays of Objects • A UML diagram for the Tunes program: Tunes CDCollection - collection : CD[] - count : int - totalCost : double + main (args : String[]) : void + addCD (title : String, artist : String, cost : double, tracks : int) : void + toString() : String - increaseSize() : void CD - title : String - artist : String - cost : double - tracks : int 1 * + toString() : String © 2004 Pearson Addison-Wesley. All rights reserved 7-25 Command-Line Arguments • The signature of the main method indicates that it takes an array of String objects as a parameter • These values come from command-line arguments that are provided when the interpreter is invoked • For example, the following invocation of the interpreter passes three String objects into main: > java StateEval pennsylvania texas arizona • These strings are stored at indexes 0-2 of the array parameter of the main method • See NameTag.java (page 393) © 2004 Pearson Addison-Wesley. All rights reserved 7-26 Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events © 2004 Pearson Addison-Wesley. All rights reserved 7-27 Variable Length Parameter Lists • Suppose we wanted to create a method that processed a different amount of data from one invocation to the next • For example, let's define a method called average that returns the average of a set of integer parameters // one call to average three values mean1 = average (42, 69, 37); // another call to average seven values mean2 = average (35, 43, 93, 23, 40, 21, 75); © 2004 Pearson Addison-Wesley. All rights reserved 7-28 Variable Length Parameter Lists • We could define overloaded versions of the average method Downside: we'd need a separate version of the method for each parameter count • We could define the method to accept an array of integers Downside: we'd have to create the array and store the integers prior to calling the method each time • Instead, Java provides a convenient way to create variable length parameter lists © 2004 Pearson Addison-Wesley. All rights reserved 7-29 Variable Length Parameter Lists • Using special syntax in the formal parameter list, we can define a method to accept any number of parameters of the same type • For each call, the parameters are automatically put into an array for easy processing in the method Indicates a variable length parameter list public double average (int ... list) { // whatever } element array type name © 2004 Pearson Addison-Wesley. All rights reserved 7-30 Variable Length Parameter Lists public double average (int ... list) { double result = 0.0; if (list.length != 0) { int sum = 0; for (int num : list) sum += num; result = (double)num / list.length; } return result; } © 2004 Pearson Addison-Wesley. All rights reserved 7-31 Variable Length Parameter Lists • The type of the parameter can be any primitive or object type public void printGrades (Grade ... grades) { for (Grade letterGrade : grades) System.out.println (letterGrade); } © 2004 Pearson Addison-Wesley. All rights reserved 7-32 Variable Length Parameter Lists • A method that accepts a variable number of parameters can also accept other parameters • The following method accepts an int, a String object, and a variable number of double values into an array called nums public void test (int count, String name, double ... nums) { // whatever } © 2004 Pearson Addison-Wesley. All rights reserved 7-33 Variable Length Parameter Lists • The varying number of parameters must come last in the formal arguments • A single method cannot accept two sets of varying parameters • Constructors can also be set up to accept a variable number of parameters • See VariableParameters.java (page 396) • See Family.java (page 397) © 2004 Pearson Addison-Wesley. All rights reserved 7-34 Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events © 2004 Pearson Addison-Wesley. All rights reserved 7-35 Two-Dimensional Arrays • A one-dimensional array stores a list of elements • A two-dimensional array can be thought of as a table of elements, with rows and columns one dimension two dimensions © 2004 Pearson Addison-Wesley. All rights reserved 7-36 Two-Dimensional Arrays • To be precise, in Java a two-dimensional array is an array of arrays • A two-dimensional array is declared by specifying the size of each dimension separately: int[][] scores = new int[12][50]; • A array element is referenced using two index values: value = scores[3][6] • The array stored in one row can be specified using one index © 2004 Pearson Addison-Wesley. All rights reserved 7-37 Two-Dimensional Arrays Expression table Type int[][] Description table[5] int[] array of integers table[5][12] int integer 2D array of integers, or array of integer arrays • See TwoDArray.java (page 399) • See SodaSurvey.java (page 400) © 2004 Pearson Addison-Wesley. All rights reserved 7-38 Multidimensional Arrays • An array can have many dimensions – if it has more than one dimension, it is called a multidimensional array • Each dimension subdivides the previous one into the specified number of elements • Each dimension has its own length constant • Because each dimension is an array of array references, the arrays within one dimension can be of different lengths these are sometimes called ragged arrays © 2004 Pearson Addison-Wesley. All rights reserved 7-39 Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events © 2004 Pearson Addison-Wesley. All rights reserved 7-40 The ArrayList Class • The ArrayList class is part of the java.util package • Like an array, it can store a list of values and reference each one using a numeric index • However, you cannot use the bracket syntax with an ArrayList object • Furthermore, an ArrayList object grows and shrinks as needed, adjusting its capacity as necessary © 2004 Pearson Addison-Wesley. All rights reserved 7-41 The ArrayList Class • Elements can be inserted or removed with a single method invocation • When an element is inserted, the other elements "move aside" to make room • Likewise, when an element is removed, the list "collapses" to close the gap • The indexes of the elements adjust accordingly © 2004 Pearson Addison-Wesley. All rights reserved 7-42 The ArrayList Class • An ArrayList stores references to the Object class, which allows it to store any kind of object • See Beatles.java (page 405) • We can also define an ArrayList object to accept a particular type of object • The following declaration creates an ArrayList object that only stores Family objects ArrayList<Family> reunion = new ArrayList<Family> • This is an example of generics, which are discussed further in Chapter 12 © 2004 Pearson Addison-Wesley. All rights reserved 7-43 ArrayList Efficiency • The ArrayList class is implemented using an underlying array • The array is manipulated so that indexes remain continuous as elements are added or removed • If elements are added to and removed from the end of the list, this processing is fairly efficient • But as elements are inserted and removed from the front or middle of the list, the remaining elements are shifted © 2004 Pearson Addison-Wesley. All rights reserved 7-44 Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events © 2004 Pearson Addison-Wesley. All rights reserved 7-45 Polygons and Polylines • Arrays can be helpful in graphics processing • For example, they can be used to store a list of coordinates • A polygon is a multisided, closed shape • A polyline is similar to a polygon except that its endpoints do not meet, and it cannot be filled • See Rocket.java (page 409) • See RocketPanel.java (page 410) © 2004 Pearson Addison-Wesley. All rights reserved 7-46 The Polygon Class • The Polygon class can also be used to define and draw a polygon • It is part of the java.awt pacakage • Versions of the overloaded drawPolygon and fillPolygon methods take a single Polygon object as a parameter instead of arrays of coordinates • A Polygon object encapsulates the coordinates of the polygon © 2004 Pearson Addison-Wesley. All rights reserved 7-47 Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events © 2004 Pearson Addison-Wesley. All rights reserved 7-48 Mouse Events • Events related to the mouse are separated into mouse events and mouse motion events • Mouse Events: mouse pressed the mouse button is pressed down mouse released the mouse button is released mouse clicked the mouse button is pressed down and released without moving the mouse in between mouse entered the mouse pointer is moved onto (over) a component mouse exited the mouse pointer is moved off of a component © 2004 Pearson Addison-Wesley. All rights reserved 7-49 Mouse Events • Mouse Motion Events: mouse moved the mouse is moved mouse dragged the mouse is moved while the mouse button is pressed down • Listeners for mouse events are created using the MouseListener and MouseMotionListener interfaces • A MouseEvent object is passed to the appropriate method when a mouse event occurs © 2004 Pearson Addison-Wesley. All rights reserved 7-50 Mouse Events • For a given program, we may only care about one or two mouse events • To satisfy the implementation of a listener interface, empty methods must be provided for unused events • See Dots.java (page 413) • See DotsPanel.java (page 414) © 2004 Pearson Addison-Wesley. All rights reserved 7-51 Mouse Events • Rubberbanding is the visual effect in which a shape is "stretched" as it is drawn using the mouse • The following example continually redraws a line as the mouse is dragged • See RubberLines.java (page 417) • See RubberLinesPanel.java (page 418) © 2004 Pearson Addison-Wesley. All rights reserved 7-52 Key Events • A key event is generated when the user types on the keyboard key pressed a key on the keyboard is pressed down key released a key on the keyboard is released key typed a key on the keyboard is pressed down and released • Listeners for key events are created by implementing the KeyListener interface • A KeyEvent object is passed to the appropriate method when a key event occurs © 2004 Pearson Addison-Wesley. All rights reserved 7-53 Key Events • The component that generates a key event is the one that has the current keyboard focus • Constants in the KeyEvent class can be used to determine which key was pressed • The following example "moves" an image of an arrow as the user types the keyboard arrow keys • See Direction.java (page 421) • See DirectionPanel.java (page 422) © 2004 Pearson Addison-Wesley. All rights reserved 7-54 Summary • Chapter 7 has focused on: array declaration and use bounds checking and capacity arrays that store object references variable length parameter lists multidimensional arrays the ArrayList class polygons and polylines mouse events and keyboard events © 2004 Pearson Addison-Wesley. All rights reserved 7-55 Chapter 8 Inheritance Inheritance • Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes • Chapter 8 focuses on: deriving new classes from existing classes the protected modifier creating class hierarchies abstract classes indirect visibility of inherited members designing for inheritance the GUI component class hierarchy extending listener adapter classes the Timer class © 2004 Pearson Addison-Wesley. All rights reserved 7-57 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance and Visibility Designing for Inheritance Inheritance and GUIs The Timer Class © 2004 Pearson Addison-Wesley. All rights reserved 7-58 Inheritance • Inheritance allows a software developer to derive a new class from an existing one • The existing class is called the parent class, or superclass, or base class • The derived class is called the child class or subclass • As the name implies, the child inherits characteristics of the parent • That is, the child class inherits the methods and data defined by the parent class © 2004 Pearson Addison-Wesley. All rights reserved 7-59 Inheritance • Inheritance relationships are shown in a UML class diagram using a solid arrow with an unfilled triangular arrowhead pointing to the parent class Vehicle Car • Proper inheritance creates an is-a relationship, meaning the child is a more specific version of the parent © 2004 Pearson Addison-Wesley. All rights reserved 7-60 Inheritance • A programmer can tailor a derived class as needed by adding new variables or methods, or by modifying the inherited ones • Software reuse is a fundamental benefit of inheritance • By using existing software components to create new ones, we capitalize on all the effort that went into the design, implementation, and testing of the existing software © 2004 Pearson Addison-Wesley. All rights reserved 7-61 Deriving Subclasses • In Java, we use the reserved word extends to establish an inheritance relationship class Car extends Vehicle { // class contents } • See Words.java (page 440) • See Book.java (page 441) • See Dictionary.java (page 442) © 2004 Pearson Addison-Wesley. All rights reserved 7-62 The protected Modifier • Visibility modifiers affect the way that class members can be used in a child class • Variables and methods declared with private visibility cannot be referenced by name in a child class • They can be referenced in the child class if they are declared with public visibility -- but public variables violate the principle of encapsulation • There is a third visibility modifier that helps in inheritance situations: protected © 2004 Pearson Addison-Wesley. All rights reserved 7-63 The protected Modifier • The protected modifier allows a child class to reference a variable or method directly in the child class • It provides more encapsulation than public visibility, but is not as tightly encapsulated as private visibility • A protected variable is visible to any class in the same package as the parent class • The details of all Java modifiers are discussed in Appendix E • Protected variables and methods can be shown with a # symbol preceding them in UML diagrams © 2004 Pearson Addison-Wesley. All rights reserved 7-64 Class Diagram for Words Book # pages : int + pageMessage() : void Words Dictionary - definitions : int + main (args : String[]) : void © 2004 Pearson Addison-Wesley. All rights reserved + definitionMessage() : void 7-65 The super Reference • Constructors are not inherited, even though they have public visibility • Yet we often want to use the parent's constructor to set up the "parent's part" of the object • The super reference can be used to refer to the parent class, and often is used to invoke the parent's constructor • See Words2.java (page 445) • See Book2.java (page 446) • See Dictionary2.java (page 447) © 2004 Pearson Addison-Wesley. All rights reserved 7-66 The super Reference • A child’s constructor is responsible for calling the parent’s constructor • The first line of a child’s constructor should use the super reference to call the parent’s constructor • The super reference can also be used to reference other variables and methods defined in the parent’s class © 2004 Pearson Addison-Wesley. All rights reserved 7-67 Multiple Inheritance • Java supports single inheritance, meaning that a derived class can have only one parent class • Multiple inheritance allows a class to be derived from two or more classes, inheriting the members of all parents • Collisions, such as the same variable name in two parents, have to be resolved • Java does not support multiple inheritance • In most cases, the use of interfaces gives us aspects of multiple inheritance without the overhead © 2004 Pearson Addison-Wesley. All rights reserved 7-68 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance and Visibility Designing for Inheritance Inheritance and GUIs The Timer Class © 2004 Pearson Addison-Wesley. All rights reserved 7-69 Overriding Methods • A child class can override the definition of an inherited method in favor of its own • The new method must have the same signature as the parent's method, but can have a different body • The type of the object executing the method determines which version of the method is invoked • See Messages.java (page 450) • See Thought.java (page 451) • See Advice.java (page 452) © 2004 Pearson Addison-Wesley. All rights reserved 7-70 Overriding • A method in the parent class can be invoked explicitly using the super reference • If a method is declared with the final modifier, it cannot be overridden • The concept of overriding can be applied to data and is called shadowing variables • Shadowing variables should be avoided because it tends to cause unnecessarily confusing code © 2004 Pearson Addison-Wesley. All rights reserved 7-71 Overloading vs. Overriding • Overloading deals with multiple methods with the same name in the same class, but with different signatures • Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature • Overloading lets you define a similar operation in different ways for different parameters • Overriding lets you define a similar operation in different ways for different object types © 2004 Pearson Addison-Wesley. All rights reserved 7-72 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance and Visibility Designing for Inheritance Inheritance and GUIs The Timer Class © 2004 Pearson Addison-Wesley. All rights reserved 7-73 Class Hierarchies • A child class of one parent can be the parent of another child, forming a class hierarchy Business RetailBusiness KMart Macys © 2004 Pearson Addison-Wesley. All rights reserved ServiceBusiness Kinkos 7-74 Class Hierarchies • Two children of the same parent are called siblings • Common features should be put as high in the hierarchy as is reasonable • An inherited member is passed continually down the line • Therefore, a child class inherits from all its ancestor classes • There is no single class hierarchy that is appropriate for all situations © 2004 Pearson Addison-Wesley. All rights reserved 7-75 The Object Class • A class called Object is defined in the java.lang package of the Java standard class library • All classes are derived from the Object class • If a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class • Therefore, the Object class is the ultimate root of all class hierarchies © 2004 Pearson Addison-Wesley. All rights reserved 7-76 The Object Class • The Object class contains a few useful methods, which are inherited by all classes • For example, the toString method is defined in the Object class • Every time we define the toString method, we are actually overriding an inherited definition • The toString method in the Object class is defined to return a string that contains the name of the object’s class along with some other information © 2004 Pearson Addison-Wesley. All rights reserved 7-77 The Object Class • The equals method of the Object class returns true if two references are aliases • We can override equals in any class to define equality in some more appropriate way • As we've seen, the String class defines the equals method to return true if two String objects contain the same characters • The designers of the String class have overridden the equals method inherited from Object in favor of a more useful version © 2004 Pearson Addison-Wesley. All rights reserved 7-78 Abstract Classes • An abstract class is a placeholder in a class hierarchy that represents a generic concept • An abstract class cannot be instantiated • We use the modifier abstract on the class header to declare a class as abstract: public abstract class Product { // contents } © 2004 Pearson Addison-Wesley. All rights reserved 7-79 Abstract Classes • An abstract class often contains abstract methods with no definitions (like an interface) • Unlike an interface, the abstract modifier must be applied to each abstract method • Also, an abstract class typically contains nonabstract methods with full definitions • A class declared as abstract does not have to contain abstract methods -- simply declaring it as abstract makes it so © 2004 Pearson Addison-Wesley. All rights reserved 7-80 Abstract Classes • The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstract • An abstract method cannot be defined as final or static • The use of abstract classes is an important element of software design – it allows us to establish common elements in a hierarchy that are too generic to instantiate © 2004 Pearson Addison-Wesley. All rights reserved 7-81 Interface Hierarchies • Inheritance can be applied to interfaces as well as classes • That is, one interface can be derived from another interface • The child interface inherits all abstract methods of the parent • A class implementing the child interface must define all methods from both the ancestor and child interfaces • Note that class hierarchies and interface hierarchies are distinct (they do not overlap) © 2004 Pearson Addison-Wesley. All rights reserved 7-82 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance and Visibility Designing for Inheritance Inheritance and GUIs The Timer Class © 2004 Pearson Addison-Wesley. All rights reserved 7-83 Visibility Revisited • It's important to understand one subtle issue related to inheritance and visibility • All variables and methods of a parent class, even private members, are inherited by its children • As we've mentioned, private members cannot be referenced by name in the child class • However, private members inherited by child classes exist and can be referenced indirectly © 2004 Pearson Addison-Wesley. All rights reserved 7-84 Visibility Revisited • Because the parent can refer to the private member, the child can reference it indirectly using its parent's methods • The super reference can be used to refer to the parent class, even if no object of the parent exists • See FoodAnalyzer.java (page 459) • See FoodItem.java (page 460) • See Pizza.java (page 461) © 2004 Pearson Addison-Wesley. All rights reserved 7-85 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance and Visibility Designing for Inheritance Inheritance and GUIs The Timer Class © 2004 Pearson Addison-Wesley. All rights reserved 7-86 Designing for Inheritance • As we've discussed, taking the time to create a good software design reaps long-term benefits • Inheritance issues are an important part of an object-oriented design • Properly designed inheritance relationships can contribute greatly to the elegance, maintainabilty, and reuse of the software • Let's summarize some of the issues regarding inheritance that relate to a good software design © 2004 Pearson Addison-Wesley. All rights reserved 7-87 Inheritance Design Issues • Every derivation should be an is-a relationship • Think about the potential future of a class hierarchy, and design classes to be reusable and flexible • Find common characteristics of classes and push them as high in the class hierarchy as appropriate • Override methods as appropriate to tailor or change the functionality of a child • Add new variables to children, but don't redefine (shadow) inherited variables © 2004 Pearson Addison-Wesley. All rights reserved 7-88 Inheritance Design Issues • Allow each class to manage its own data; use the super reference to invoke the parent's constructor to set up its data • Even if there are no current uses for them, override general methods such as toString and equals with appropriate definitions • Use abstract classes to represent general concepts that lower classes have in common • Use visibility modifiers carefully to provide needed access without violating encapsulation © 2004 Pearson Addison-Wesley. All rights reserved 7-89 Restricting Inheritance • The final modifier can be used to curtail inheritance • If the final modifier is applied to a method, then that method cannot be overridden in any descendent classes • If the final modifier is applied to an entire class, then that class cannot be used to derive any children at all Thus, an abstract class cannot be declared as final • These are key design decisions, establishing that a method or class should be used as is © 2004 Pearson Addison-Wesley. All rights reserved 7-90 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance and Visibility Designing for Inheritance Inheritance and GUIs The Timer Class © 2004 Pearson Addison-Wesley. All rights reserved 7-91 The Component Class Hierarchy • The Java classes that define GUI components are part of a class hierarchy • Swing GUI components typically are derived from the JComponent class which is derived from the Container class which is derived from the Component class • Many Swing components can serve as (limited) containers, because they are derived from the Container class • For example, a JLabel object can contain an ImageIcon © 2004 Pearson Addison-Wesley. All rights reserved 7-92 The Component Class Hierarchy • An applet is a good example of inheritance • Recall that when we define an applet, we extend the Applet class or the JApplet class • The Applet and JApplet classes already handle all the details about applet creation and execution, including: interaction with a Web browser accepting applet parameters through HTML enforcing security restrictions © 2004 Pearson Addison-Wesley. All rights reserved 7-93 The Component Class Hierarchy • Our applet classes only have to deal with issues that specifically relate to what our particular applet will do • When we define paintComponent method of an applet, we are actually overriding a method defined originally in the JComponent class and inherited by the JApplet class © 2004 Pearson Addison-Wesley. All rights reserved 7-94 Event Adapter Classes • Inheritance also gives us a alternate technique for creating listener classes • We've seen that listener classes can be created by implementing a particular interface, such as MouseListener • We can also create a listener class by extending an event adapter class • Each listener interface that has more than one method has a corresponding adapter class, such as the MouseAdapter class © 2004 Pearson Addison-Wesley. All rights reserved 7-95 Event Adapter Classes • Each adapter class implements the corresponding listener and provides empty method definitions • When you derive a listener class from an adapter class, you only need to override the event methods that pertain to the program • Empty definitions for unused event methods do not need to be defined because they are provided via inheritance • See OffCenter.java (page 466) • See OffCenterPanel.java (page 467) © 2004 Pearson Addison-Wesley. All rights reserved 7-96 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance and Visibility Designing for Inheritance Inheritance and GUIs The Timer Class © 2004 Pearson Addison-Wesley. All rights reserved 7-97 The Timer Class • The Timer class of the javax.swing package is a GUI component, but it has no visual representation • A Timer object generates an action event at specified intervals • Timers can be used to manage any events that are based on a timed interval, such as an animation • To create the illusion of movement, we use a timer to change the scene after an appropriate delay © 2004 Pearson Addison-Wesley. All rights reserved 7-98 The Timer Class • The start and stop methods of the Timer class start and stop the timer • The delay can be set using the Timer constructor or using the setDelay method • See Rebound.java (page 471) • See ReboundPanel.java (page 472) © 2004 Pearson Addison-Wesley. All rights reserved 7-99 Summary • Chapter 8 focused on: deriving new classes from existing classes the protected modifier creating class hierarchies abstract classes indirect visibility of inherited members designing for inheritance the GUI component class hierarchy extending listener adapter classes the Timer class © 2004 Pearson Addison-Wesley. All rights reserved 7-100 Chapter 9 Polymorphism Polymorphism • Polymorphism is an object-oriented concept that allows us to create versatile software designs • Chapter 9 focuses on: defining polymorphism and its benefits using inheritance to create polymorphic references using interfaces to create polymorphic references using polymorphism to implement sorting and searching algorithms additional GUI components © 2004 Pearson Addison-Wesley. All rights reserved 7-102 Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and Color Choosers Sliders © 2004 Pearson Addison-Wesley. All rights reserved 7-103 Binding • Consider the following method invocation: obj.doIt(); • At some point, this invocation is bound to the definition of the method that it invokes • If this binding occurred at compile time, then that line of code would call the same method every time • However, Java defers method binding until run time -- this is called dynamic binding or late binding • Late binding provides flexibility in program design © 2004 Pearson Addison-Wesley. All rights reserved 7-104 Polymorphism • The term polymorphism literally means "having many forms" • A polymorphic reference is a variable that can refer to different types of objects at different points in time • The method invoked through a polymorphic reference can change from one invocation to the next • All object references in Java are potentially polymorphic © 2004 Pearson Addison-Wesley. All rights reserved 7-105 Polymorphism • Suppose we create the following reference variable: Occupation job; • Java allows this reference to point to an Occupation object, or to any object of any compatible type • This compatibility can be established using inheritance or using interfaces • Careful use of polymorphic references can lead to elegant, robust software designs © 2004 Pearson Addison-Wesley. All rights reserved 7-106 Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and Color Choosers Sliders © 2004 Pearson Addison-Wesley. All rights reserved 7-107 References and Inheritance • An object reference can refer to an object of its class, or to an object of any class related to it by inheritance • For example, if the Holiday class is used to derive a class called Christmas, then a Holiday reference could be used to point to a Christmas object Holiday Holiday day; day = new Christmas(); Christmas © 2004 Pearson Addison-Wesley. All rights reserved 7-108 References and Inheritance • Assigning a child object to a parent reference is considered to be a widening conversion, and can be performed by simple assignment • Assigning an parent object to a child reference can be done also, but it is considered a narrowing conversion and must be done with a cast • The widening conversion is the most useful © 2004 Pearson Addison-Wesley. All rights reserved 7-109 Polymorphism via Inheritance • It is the type of the object being referenced, not the reference type, that determines which method is invoked • Suppose the Holiday class has a method called celebrate, and the Christmas class overrides it • Now consider the following invocation: day.celebrate(); • If day refers to a Holiday object, it invokes the Holiday version of celebrate; if it refers to a Christmas object, it invokes the Christmas version © 2004 Pearson Addison-Wesley. All rights reserved 7-110 Polymorphism via Inheritance • Consider the following class hierarchy: StaffMember Volunteer Employee Executive © 2004 Pearson Addison-Wesley. All rights reserved Hourly 7-111 Polymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic method • • • • • • • See Firm.java (page 486) See Staff.java (page 487) See StaffMember.java (page 489) See Volunteer.java (page 491) See Employee.java (page 492) See Executive.java (page 493) See Hourly.java (page 494) © 2004 Pearson Addison-Wesley. All rights reserved 7-112 Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and Color Choosers Sliders © 2004 Pearson Addison-Wesley. All rights reserved 7-113 Polymorphism via Interfaces • An interface name can be used as the type of an object reference variable Speaker current; • The current reference can be used to point to any object of any class that implements the Speaker interface • The version of speak that the following line invokes depends on the type of object that current is referencing current.speak(); © 2004 Pearson Addison-Wesley. All rights reserved 7-114 Polymorphism via Interfaces • Suppose two classes, Philosopher and Dog, both implement the Speaker interface, providing distinct versions of the speak method • In the following code, the first call to speak invokes one version and the second invokes another: Speaker guest = new Philospher(); guest.speak(); guest = new Dog(); guest.speak(); © 2004 Pearson Addison-Wesley. All rights reserved 7-115 Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and Color Choosers Sliders © 2004 Pearson Addison-Wesley. All rights reserved 7-116 Sorting • Sorting is the process of arranging a list of items in a particular order • The sorting process is based on specific value(s) sorting a list of test scores in ascending numeric order sorting a list of people alphabetically by last name • There are many algorithms, which vary in efficiency, for sorting a list of items • We will examine two specific algorithms: Selection Sort Insertion Sort © 2004 Pearson Addison-Wesley. All rights reserved 7-117 Selection Sort • The approach of Selection Sort: select a value and put it in its final place into the list repeat for all other values • In more detail: find the smallest value in the list switch it with the value in the first position find the next smallest value in the list switch it with the value in the second position repeat until all values are in their proper places © 2004 Pearson Addison-Wesley. All rights reserved 7-118 Selection Sort • An example: original: smallest is smallest is smallest is smallest is 1: 2: 3: 6: 3 1 1 1 1 9 9 2 2 2 6 6 6 3 3 1 3 3 6 6 2 2 9 9 9 • Each time, the smallest remaining value is found and exchanged with the element in the "next" position to be filled © 2004 Pearson Addison-Wesley. All rights reserved 7-119 Swapping • The processing of the selection sort algorithm includes the swapping of two values • Swapping requires three assignment statements and a temporary storage location: temp = first; first = second; second = temp; © 2004 Pearson Addison-Wesley. All rights reserved 7-120 Polymorphism in Sorting • Recall that an class that implements the Comparable interface defines a compareTo method to determine the relative order of its objects • We can use polymorphism to develop a generic sort for any set of Comparable objects • The sorting method accepts as a parameter an array of Comparable objects • That way, one method can be used to sort a group of People, or Books, or whatever © 2004 Pearson Addison-Wesley. All rights reserved 7-121 Selection Sort • The sorting method doesn't "care" what it is sorting, it just needs to be able to call the compareTo method • That is guaranteed by using Comparable as the parameter type • Also, this way each class decides for itself what it means for one object to be less than another • See PhoneList.java (page 500) • See Sorting.java (page 501), specifically the selectionSort method • See Contact.java (page 503) © 2004 Pearson Addison-Wesley. All rights reserved 7-122 Insertion Sort • The approach of Insertion Sort: pick any item and insert it into its proper place in a sorted sublist repeat until all items have been inserted • In more detail: consider the first item to be a sorted sublist (of one item) insert the second item into the sorted sublist, shifting the first item as needed to make room to insert the new addition insert the third item into the sorted sublist (of two items), shifting items as necessary repeat until all values are inserted into their proper positions © 2004 Pearson Addison-Wesley. All rights reserved 7-123 Insertion Sort • An example: original: insert 9: insert 6: insert 1: insert 2: 3 3 3 1 1 9 9 6 3 2 6 6 9 6 3 1 1 1 9 6 2 2 2 2 9 • See Sorting.java (page 501), specifically the insertionSort method © 2004 Pearson Addison-Wesley. All rights reserved 7-124 Comparing Sorts • The Selection and Insertion sort algorithms are similar in efficiency • They both have outer loops that scan all elements, and inner loops that compare the value of the outer loop with almost all values in the list • Approximately n2 number of comparisons are made to sort a list of size n • We therefore say that these sorts are of order n2 • Other sorts are more efficient: order n log2 n © 2004 Pearson Addison-Wesley. All rights reserved 7-125 Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and Color Choosers Sliders © 2004 Pearson Addison-Wesley. All rights reserved 7-126 Searching • Searching is the process of finding a target element within a group of items called the search pool • The target may or may not be in the search pool • We want to perform the search efficiently, minimizing the number of comparisons • Let's look at two classic searching approaches: linear search and binary search • As we did with sorting, we'll implement the searches with polymorphic Comparable parameters © 2004 Pearson Addison-Wesley. All rights reserved 7-127 Linear Search • A linear search begins at one end of a list and examines each element in turn • Eventually, either the item is found or the end of the list is encountered • See PhoneList2.java (page 508) • See Searching.java (page 509), specifically the linearSearch method © 2004 Pearson Addison-Wesley. All rights reserved 7-128 Binary Search • A binary search assumes the list of items in the search pool is sorted • It eliminates a large part of the search pool with a single comparison • A binary search first examines the middle element of the list -- if it matches the target, the search is over • If it doesn't, only one half of the remaining elements need be searched • Since they are sorted, the target can only be in one half of the other © 2004 Pearson Addison-Wesley. All rights reserved 7-129 Binary Search • The process continues by comparing the middle element of the remaining viable candidates • Each comparison eliminates approximately half of the remaining data • Eventually, the target is found or the data is exhausted • See PhoneList2.java (page 508) • See Searching.java (page 509), specifically the binarySearch method © 2004 Pearson Addison-Wesley. All rights reserved 7-130 Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and Color Choosers Sliders © 2004 Pearson Addison-Wesley. All rights reserved 7-131 Event Processing • Polymorphism plays an important role in the development of a Java graphical user interface • As we've seen, we establish a relationship between a component and a listener: JButton button = new JButton(); button.addActionListener(new MyListener()); • Note that the addActionListener method is accepting a MyListener object as a parameter • In fact, we can pass the addActionListener method any object that implements the ActionListener interface © 2004 Pearson Addison-Wesley. All rights reserved 7-132 Event Processing • The source code for the addActionListener method accepts a parameter of type ActionListener (the interface) • Because of polymorphism, any object that implements that interface is compatible with the parameter reference variable • The component can call the actionPerformed method because of the relationship between the listener class and the interface • Extending an adapter class to create a listener represents the same situation; the adapter class implements the appropriate interface already © 2004 Pearson Addison-Wesley. All rights reserved 7-133 Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and Color Choosers Sliders © 2004 Pearson Addison-Wesley. All rights reserved 7-134 Dialog Boxes • Recall that a dialog box is a small window that "pops up" to interact with the user for a brief, specific purpose • The JOptionPane class makes it easy to create dialog boxes for presenting information, confirming an action, or accepting an input value • Let's now look at two other classes that let us create specialized dialog boxes © 2004 Pearson Addison-Wesley. All rights reserved 7-135 File Choosers • Situations often arise where we want the user to select a file stored on a disk drive, usually so that its contents can be read and processed • A file chooser, represented by the JFileChooser class, simplifies this process • The user can browse the disk and filter the file types displayed • See DisplayFile.java (page 516) © 2004 Pearson Addison-Wesley. All rights reserved 7-136 Color Choosers • In many situations we want to allow the user to select a color • A color chooser , represented by the JColorChooser class, simplifies this process • The user can choose a color from a palette or specify the color using RGB values • See DisplayColor.java (page 519) © 2004 Pearson Addison-Wesley. All rights reserved 7-137 Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and Color Choosers Sliders © 2004 Pearson Addison-Wesley. All rights reserved 7-138 Sliders • A slider is a GUI component that allows the user to specify a value within a numeric range • A slider can be oriented vertically or horizontally and can have optional tick marks and labels • The minimum and maximum values for the slider are set using the JSlider constructor • A slider produces a change event when the slider is moved, indicating that the slider and the value it represents has changed © 2004 Pearson Addison-Wesley. All rights reserved 7-139 Sliders • The following example uses three sliders to change values representing the color components of an RGB value • See SlideColor.java (page 522) • See SlideColorPanel.java (page 523) © 2004 Pearson Addison-Wesley. All rights reserved 7-140 Summary • Chapter 9 has focused on: defining polymorphism and its benefits using inheritance to create polymorphic references using interfaces to create polymorphic references using polymorphism to implement sorting and searching algorithms additional GUI components © 2004 Pearson Addison-Wesley. All rights reserved 7-141 Chapter 10 Exceptions Exceptions • Exception handling is an important aspect of object-oriented design • Chapter 10 focuses on: the purpose of exceptions exception messages the try-catch statement propagating exceptions the exception class hierarchy GUI mnemonics and tool tips more GUI components and containers © 2004 Pearson Addison-Wesley. All rights reserved 7-143 Outline Exception Handling The try-catch Statement Exception Classes I/O Exceptions Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes © 2004 Pearson Addison-Wesley. All rights reserved 7-144 Exceptions • An exception is an object that describes an unusual or erroneous situation • Exceptions are thrown by a program, and may be caught and handled by another part of the program • A program can be separated into a normal execution flow and an exception execution flow • An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught © 2004 Pearson Addison-Wesley. All rights reserved 7-145 Exception Handling • Java has a predefined set of exceptions and errors that can occur during execution • A program can deal with an exception in one of three ways: ignore it handle it where it occurs handle it an another place in the program • The manner in which an exception is processed is an important design consideration © 2004 Pearson Addison-Wesley. All rights reserved 7-146 Exception Handling • If an exception is ignored by the program, the program will terminate abnormally and produce an appropriate message • The message includes a call stack trace that: indicates the line on which the exception occurred shows the method call trail that lead to the attempted execution of the offending line • See Zero.java (page 533) © 2004 Pearson Addison-Wesley. All rights reserved 7-147 Outline Exception Handling The try-catch Statement Exception Classes I/O Exceptions Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes © 2004 Pearson Addison-Wesley. All rights reserved 7-148 The try Statement • To handle an exception in a program, the line that throws the exception is executed within a try block • A try block is followed by one or more catch clauses • Each catch clause has an associated exception type and is called an exception handler • When an exception occurs, processing continues at the first catch clause that matches the exception type • See ProductCodes.java (page 536) © 2004 Pearson Addison-Wesley. All rights reserved 7-149 The finally Clause • A try statement can have an optional clause following the catch clauses, designated by the reserved word finally • The statements in the finally clause always are executed • If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete • If an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete © 2004 Pearson Addison-Wesley. All rights reserved 7-150 Exception Propagation • An exception can be handled at a higher level if it is not appropriate to handle it where it occurs • Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the level of the main method • A try block that contains a call to a method in which an exception is thrown can be used to catch that exception • See Propagation.java (page 539) • See ExceptionScope.java (page 540) © 2004 Pearson Addison-Wesley. All rights reserved 7-151 Outline Exception Handling The try-catch Statement Exception Classes I/O Exceptions Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes © 2004 Pearson Addison-Wesley. All rights reserved 7-152 The Exception Class Hierarchy • Classes that define exceptions are related by inheritance, forming an exception class hierarchy • All error and exception classes are descendents of the Throwable class • A programmer can define an exception by extending the Exception class or one of its descendants • The parent class used depends on how the new exception will be used © 2004 Pearson Addison-Wesley. All rights reserved 7-153 Checked Exceptions • An exception is either checked or unchecked • A checked exception either must be caught by a method, or must be listed in the throws clause of any method that may throw or propagate it • A throws clause is appended to the method header • The compiler will issue an error if a checked exception is not caught or asserted in a throws clause © 2004 Pearson Addison-Wesley. All rights reserved 7-154 Unchecked Exceptions • An unchecked exception does not require explicit handling, though it could be processed that way • The only unchecked exceptions in Java are objects of type RuntimeException or any of its descendants • Errors are similar to RuntimeException and its descendants in that: Errors should not be caught Errors do not require a throws clause © 2004 Pearson Addison-Wesley. All rights reserved 7-155 The throw Statement • Exceptions are thrown using the throw statement • Usually a throw statement is executed inside an if statement that evaluates a condition to see if the exception should be thrown • See CreatingExceptions.java (page 543) • See OutOfRangeException.java (page 544) © 2004 Pearson Addison-Wesley. All rights reserved 7-156 Outline Exception Handling The try-catch Statement Exception Classes I/O Exceptions Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes © 2004 Pearson Addison-Wesley. All rights reserved 7-157 I/O Exceptions • Let's examine issues related to exceptions and I/O • A stream is a sequence of bytes that flow from a source to a destination • In a program, we read information from an input stream and write information to an output stream • A program can manage multiple streams simultaneously © 2004 Pearson Addison-Wesley. All rights reserved 7-158 Standard I/O • There are three standard I/O streams: standard output – defined by System.out standard input – defined by System.in standard error – defined by System.err • We use System.out when we execute println statements • System.out and System.err typically represent a particular window on the monitor screen • System.in typically represents keyboard input, which we've used many times with Scanner objects © 2004 Pearson Addison-Wesley. All rights reserved 7-159 The IOException Class • Operations performed by some I/O classes may throw an IOException A file might not exist Even if the file exists, a program may not be able to find it The file might not contain the kind of data we expect • An IOException is a checked exception © 2004 Pearson Addison-Wesley. All rights reserved 7-160 Writing Text Files • In Chapter 5 we explored the use of the Scanner class to read input from a text file • Let's now examine other classes that let us write data to a text file • The FileWriter class represents a text output file, but with minimal support for manipulating data • Therefore, we also rely on PrintStream objects, which have print and println methods defined for them © 2004 Pearson Addison-Wesley. All rights reserved 7-161 Writing Text Files • Finally, we'll also use the PrintWriter class for advanced internationalization and error checking • We build the class that represents the output file by combining these classes appropriately • See TestData.java (page 547) • Output streams should be closed explicitly © 2004 Pearson Addison-Wesley. All rights reserved 7-162 Outline Exception Handling The try-catch Statement Exception Classes I/O Exceptions Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes © 2004 Pearson Addison-Wesley. All rights reserved 7-163 Tool Tips • A tool tip provides a short pop-up description when the mouse cursor rests momentarily on a component • A tool tip is assigned using the setToolTipText method of a Swing component JButton button = new JButton ("Compute"); button.setToolTipText ("Calculate size"); © 2004 Pearson Addison-Wesley. All rights reserved 7-164 Mnemonics • A mnemonic is a keyboard alternative for pushing a button or selecting a menu option • The mnemonic character should be chosen from the component's label, and is underlined • The user activates the component by holding down the ALT key and pressing the mnemonic character • A mnemonic is established using the setMnemonic method: JButton button = new JButton ("Calculate"); button.setMnemonic ("C"); © 2004 Pearson Addison-Wesley. All rights reserved 7-165 Disabled Components • Components can be disabled if they should not be used • A disabled component is "grayed out" and will not respond to user interaction • The status is set using the setEnabled method: JButton button = new JButton (“Do It”); button.setEnabled (false); © 2004 Pearson Addison-Wesley. All rights reserved 7-166 GUI Design • The right combination of special features such as tool tips and mnemonics can enhance the usefulness of a GUI • See LightBulb.java (page 551) • See LightBulbPanel.java (page 553) • See LightBulbControls.java (page 554) © 2004 Pearson Addison-Wesley. All rights reserved 7-167 Outline Exception Handling The try-catch Statement Exception Classes I/O Exceptions Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes © 2004 Pearson Addison-Wesley. All rights reserved 7-168 Combo Boxes • A combo box provides a menu from which the user can choose one of several options • The currently selected option is shown in the combo box • A combo box shows its options only when the user presses it using the mouse • Options can be established using an array of strings or using the addItem method © 2004 Pearson Addison-Wesley. All rights reserved 7-169 The JukeBox Program • A combo box generates an action event when the user makes a selection from it • See JukeBox.java (page 557) • See JukeBoxControls.java (page 559) © 2004 Pearson Addison-Wesley. All rights reserved 7-170 Outline Exception Handling The try-catch Statement Exception Classes I/O Exceptions Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes © 2004 Pearson Addison-Wesley. All rights reserved 7-171 Scroll Panes • A scroll pane is useful for images or information too large to fit in a reasonably-sized area • A scroll pane offers a limited view of the component it contains • It provides vertical and/or horizontal scroll bars that allow the user to scroll to other areas of the component • No event listener is needed for a scroll pane • See TransitMap.java (page 562) © 2004 Pearson Addison-Wesley. All rights reserved 7-172 Split Panes • A split pane (JSplitPane) is a container that displays two components separated by a moveable divider bar • The two components can be displayed side by side, or one on top of the other Moveable Divider Bar Top Component Left Component Right Component Bottom Component © 2004 Pearson Addison-Wesley. All rights reserved 7-173 Split Panes • The orientation of the split pane is set using the HORIZONTAL_SPLIT or VERTICAL_SPLIT constants • The divider bar can be set so that it can be fully expanded with one click of the mouse • The components can be continuously adjusted as the divider bar is moved, or wait until it stops moving • Split panes can be nested © 2004 Pearson Addison-Wesley. All rights reserved 7-174 Lists • The Swing Jlist class represents a list of items from which the user can choose • The contents of a JList object can be specified using an array of objects • A JList object generates a list selection event when the current selection changes • See PickImage.java (page 566) • See ListPanel.java (page 568) © 2004 Pearson Addison-Wesley. All rights reserved 7-175 Lists • A JList object can be set so that multiple items can be selected at the same time • The list selection mode can be one of three options: single selection – only one item can be selected at a time single interval selection – multiple, contiguous items can be selected at a time multiple interval selection – any combination of items can be selected • The list selection mode is defined by a ListSelectionModel object © 2004 Pearson Addison-Wesley. All rights reserved 7-176 Summary • Chapter 10 has focused on: • • • • • • • the purpose of exceptions exception messages the try-catch statement propagating exceptions the exception class hierarchy GUI mnemonics and tool tips more GUI components and containers © 2004 Pearson Addison-Wesley. All rights reserved 7-177 Chapter 11 Recursion Recursion • Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems • Chapter 11 focuses on: thinking in a recursive manner programming in a recursive manner the correct use of recursion recursion examples © 2004 Pearson Addison-Wesley. All rights reserved 7-179 Outline Recursive Thinking Recursive Programming Using Recursion Recursion in Graphics © 2004 Pearson Addison-Wesley. All rights reserved 7-180 Recursive Thinking • A recursive definition is one which uses the word or concept being defined in the definition itself • When defining an English word, a recursive definition is often not helpful • But in other situations, a recursive definition can be an appropriate way to express a concept • Before applying recursion to programming, it is best to practice thinking recursively © 2004 Pearson Addison-Wesley. All rights reserved 7-181 Recursive Definitions • Consider the following list of numbers: 24, 88, 40, 37 • Such a list can be defined as follows: A LIST is a: or a: number number comma LIST • That is, a LIST is defined to be a single number, or a number followed by a comma followed by a LIST • The concept of a LIST is used to define itself © 2004 Pearson Addison-Wesley. All rights reserved 7-182 Recursive Definitions • The recursive part of the LIST definition is used several times, terminating with the non-recursive part: number comma LIST 24 , 88, 40, 37 number comma LIST 88 , 40, 37 number comma LIST 40 , 37 number 37 © 2004 Pearson Addison-Wesley. All rights reserved 7-183 Infinite Recursion • All recursive definitions have to have a nonrecursive part • If they didn't, there would be no way to terminate the recursive path • Such a definition would cause infinite recursion • This problem is similar to an infinite loop, but the non-terminating "loop" is part of the definition itself • The non-recursive part is often called the base case © 2004 Pearson Addison-Wesley. All rights reserved 7-184 Recursive Definitions • N!, for any positive integer N, is defined to be the product of all integers between 1 and N inclusive • This definition can be expressed recursively as: 1! N! = = 1 N * (N-1)! • A factorial is defined in terms of another factorial • Eventually, the base case of 1! is reached © 2004 Pearson Addison-Wesley. All rights reserved 7-185 Recursive Definitions 5! 120 5 * 4! 24 4 * 3! 6 3 * 2! 2 2 * 1! 1 © 2004 Pearson Addison-Wesley. All rights reserved 7-186 Outline Recursive Thinking Recursive Programming Using Recursion Recursion in Graphics © 2004 Pearson Addison-Wesley. All rights reserved 7-187 Recursive Programming • A method in Java can invoke itself; if set up that way, it is called a recursive method • The code of a recursive method must be structured to handle both the base case and the recursive case • Each call to the method sets up a new execution environment, with new parameters and local variables • As with any method call, when the method completes, control returns to the method that invoked it (which may be an earlier invocation of itself) © 2004 Pearson Addison-Wesley. All rights reserved 7-188 Recursive Programming • Consider the problem of computing the sum of all the numbers between 1 and any positive integer N • This problem can be recursively defined as: N i N i 1 N 1 i N N 1 i 1 N N 1 N 2 N 3 N 2 i i 1 i i 1 © 2004 Pearson Addison-Wesley. All rights reserved 7-189 Recursive Programming // This method returns the sum of 1 to num public int sum (int num) { int result; if (num == 1) result = 1; else result = num + sum (n-1); return result; } © 2004 Pearson Addison-Wesley. All rights reserved 7-190 Recursive Programming result = 6 main sum(3) sum result = 3 sum(2) sum result = 1 sum(1) sum © 2004 Pearson Addison-Wesley. All rights reserved 7-191 Recursive Programming • Note that just because we can use recursion to solve a problem, doesn't mean we should • For instance, we usually would not use recursion to solve the sum of 1 to N problem, because the iterative version is easier to understand • However, for some problems, recursion provides an elegant solution, often cleaner than an iterative version • You must carefully decide whether recursion is the correct technique for any problem © 2004 Pearson Addison-Wesley. All rights reserved 7-192 Indirect Recursion • A method invoking itself is considered to be direct recursion • A method could invoke another method, which invokes another, etc., until eventually the original method is invoked again • For example, method m1 could invoke m2, which invokes m3, which in turn invokes m1 again • This is called indirect recursion, and requires all the same care as direct recursion • It is often more difficult to trace and debug © 2004 Pearson Addison-Wesley. All rights reserved 7-193 Indirect Recursion m1 m2 m3 m1 m2 m1 © 2004 Pearson Addison-Wesley. All rights reserved m3 m2 m3 7-194 Outline Recursive Thinking Recursive Programming Using Recursion Recursion in Graphics © 2004 Pearson Addison-Wesley. All rights reserved 7-195 Maze Traversal • We can use recursion to find a path through a maze • From each location, we can search in each direction • Recursion keeps track of the path through the maze • The base case is an invalid move or reaching the final destination • See MazeSearch.java (page 583) • See Maze.java (page 584) © 2004 Pearson Addison-Wesley. All rights reserved 7-196 Towers of Hanoi • The Towers of Hanoi is a puzzle made up of three vertical pegs and several disks that slide on the pegs • The disks are of varying size, initially placed on one peg with the largest disk on the bottom with increasingly smaller ones on top • The goal is to move all of the disks from one peg to another under the following rules: We can move only one disk at a time We cannot move a larger disk on top of a smaller one © 2004 Pearson Addison-Wesley. All rights reserved 7-197 Towers of Hanoi Original Configuration Move 1 Move 2 Move 3 © 2004 Pearson Addison-Wesley. All rights reserved 7-198 Towers of Hanoi Move 4 Move 5 Move 6 Move 7 (done) © 2004 Pearson Addison-Wesley. All rights reserved 7-199 Towers of Hanoi • An iterative solution to the Towers of Hanoi is quite complex • A recursive solution is much shorter and more elegant • See SolveTowers.java (page 590) • See TowersOfHanoi.java (page 591) © 2004 Pearson Addison-Wesley. All rights reserved 7-200 Outline Recursive Thinking Recursive Programming Using Recursion Recursion in Graphics © 2004 Pearson Addison-Wesley. All rights reserved 7-201 Tiled Pictures • Consider the task of repeatedly displaying a set of images in a mosaic Three quadrants contain individual images Upper-left quadrant repeats pattern • The base case is reached when the area for the images shrinks to a certain size • See TiledPictures.java (page 594) © 2004 Pearson Addison-Wesley. All rights reserved 7-202 Tiled Pictures © 2004 Pearson Addison-Wesley. All rights reserved 7-203 Fractals • A fractal is a geometric shape made up of the same pattern repeated in different sizes and orientations • The Koch Snowflake is a particular fractal that begins with an equilateral triangle • To get a higher order of the fractal, the sides of the triangle are replaced with angled line segments • See KochSnowflake.java (page 597) • See KochPanel.java (page 600) © 2004 Pearson Addison-Wesley. All rights reserved 7-204 Koch Snowflakes < x5 , y5 > < x 5 , y5 > < x 4 , y4 > Becomes < x3 , y 3 > < x 2 , y2 > < x1 , y1 > © 2004 Pearson Addison-Wesley. All rights reserved < x 1 , y1 > 7-205 Koch Snowflakes © 2004 Pearson Addison-Wesley. All rights reserved 7-206 Koch Snowflakes © 2004 Pearson Addison-Wesley. All rights reserved 7-207 Summary • Chapter 11 has focused on: thinking in a recursive manner programming in a recursive manner the correct use of recursion recursion examples © 2004 Pearson Addison-Wesley. All rights reserved 7-208 Chapter 12 Collections Collections • A collection is an object that helps us organize and manage other objects • Chapter 12 focuses on: the concept of a collection separating the interface from the implementation dynamic data structures linked lists queues and stacks trees and graphs generics © 2004 Pearson Addison-Wesley. All rights reserved 7-210 Outline Collections and Data Structures Dynamic Representations Queues and Stacks Trees and Graphs The Java Collections API © 2004 Pearson Addison-Wesley. All rights reserved 7-211 Collections • A collection is an object that serves as a repository for other objects • A collection usually provides services such as adding, removing, and otherwise managing the elements it contains • Sometimes the elements in a collection are ordered, sometimes they are not • Sometimes collections are homogeneous, containing all the same type of objects, and sometimes they are heterogeneous © 2004 Pearson Addison-Wesley. All rights reserved 7-212 Abstraction • Collections can be implemented in many different ways • Our data structures should be abstractions • That is, they should hide unneeded details • We want to separate the interface of the structure from its underlying implementation • This helps manage complexity and makes it possible to change the implementation without changing the interface © 2004 Pearson Addison-Wesley. All rights reserved 7-213 Abstract Data Types • An abstract data type (ADT) is an organized collection of information and a set of operations used to manage that information • The set of operations defines the interface to the ADT • In one sense, as long as the ADT fulfills the promises of the interface, it doesn't matter how the ADT is implemented • Objects are a perfect programming mechanism to create ADTs because their internal details are encapsulated © 2004 Pearson Addison-Wesley. All rights reserved 7-214 Outline Collections and Data Structures Dynamic Representations Queues and Stacks Trees and Graphs The Java Collections API © 2004 Pearson Addison-Wesley. All rights reserved 7-215 Dynamic Structures • A static data structure has a fixed size • This meaning is different from the meaning of the static modifier • Arrays are static; once you define the number of elements it can hold, the size doesn’t change • A dynamic data structure grows and shrinks at execution time as required by its contents • A dynamic data structure is implemented using links © 2004 Pearson Addison-Wesley. All rights reserved 7-216 Object References • Recall that an object reference is a variable that stores the address of an object • A reference also can be called a pointer • References often are depicted graphically: student John Smith 40725 3.58 © 2004 Pearson Addison-Wesley. All rights reserved 7-217 References as Links • Object references can be used to create links between objects • Suppose a Student class contains a reference to another Student object John Smith 40725 3.57 © 2004 Pearson Addison-Wesley. All rights reserved Jane Jones 58821 3.72 7-218 References as Links • References can be used to create a variety of linked structures, such as a linked list: studentList © 2004 Pearson Addison-Wesley. All rights reserved 7-219 Intermediate Nodes • The objects being stored should not be concerned with the details of the data structure in which they may be stored • For example, the Student class should not have to store a link to the next Student object in the list • Instead, we can use a separate node class with two parts: 1) a reference to an independent object and 2) a link to the next node in the list • The internal representation becomes a linked list of nodes © 2004 Pearson Addison-Wesley. All rights reserved 7-220 Magazine Collection • Let’s explore an example of a collection of Magazine objects, managed by the MagazineList class, which has an private inner class called MagazineNode • Because the MagazineNode is private to MagazineList, the MagazineList methods can directly access MagazineNode data without violating encapsulation • See MagazineRack.java (page 615) • See MagazineList.java (page 616) • See Magazine.java (page 618) © 2004 Pearson Addison-Wesley. All rights reserved 7-221 Other Dynamic Representations • It may be convenient to implement as list as a doubly linked list, with next and previous references list © 2004 Pearson Addison-Wesley. All rights reserved 7-222 Other Dynamic Representations • It may be convenient to use a separate header node, with a count and references to both the front and rear of the list list © 2004 Pearson Addison-Wesley. All rights reserved count: 4 front rear 7-223 Outline Collections and Data Structures Dynamic Representations Queues and Stacks Trees and Graphs The Java Collections API © 2004 Pearson Addison-Wesley. All rights reserved 7-224 Classic Data Structures • Now we'll examine some classic data structures • Classic linear data structures include queues and stacks • Classic nonlinear data structures include trees and graphs © 2004 Pearson Addison-Wesley. All rights reserved 7-225 Queues • A queue is similar to a list but adds items only to the rear of the list and removes them only from the front • It is called a FIFO data structure: First-In, First-Out • Analogy: a line of people at a bank teller’s window enqueue © 2004 Pearson Addison-Wesley. All rights reserved dequeue 7-226 Queues • We can define the operations for a queue enqueue - add an item to the rear of the queue dequeue (or serve) - remove an item from the front of the queue empty - returns true if the queue is empty • As with our linked list example, by storing generic Object references, any object can be stored in the queue • Queues often are helpful in simulations or any situation in which items get “backed up” while awaiting processing © 2004 Pearson Addison-Wesley. All rights reserved 7-227 Queues • A queue can be represented by a singly-linked list; it is most efficient if the references point from the front toward the rear of the queue • A queue can be represented by an array, using the remainder operator (%) to “wrap around” when the end of the array is reached and space is available at the front of the array © 2004 Pearson Addison-Wesley. All rights reserved 7-228 Stacks • A stack ADT is also linear, like a list or a queue • Items are added and removed from only one end of a stack • It is therefore LIFO: Last-In, First-Out • Analogies: a stack of plates in a cupboard, a stack of bills to be paid, or a stack of hay bales in a barn © 2004 Pearson Addison-Wesley. All rights reserved 7-229 Stacks • Stacks often are drawn vertically: push © 2004 Pearson Addison-Wesley. All rights reserved pop 7-230 Stacks • Some stack operations: push - add an item to the top of the stack pop - remove an item from the top of the stack peek (or top) - retrieves the top item without removing it empty - returns true if the stack is empty • A stack can be represented by a singly-linked list; it doesn’t matter whether the references point from the top toward the bottom or vice versa • A stack can be represented by an array, but the new item should be placed in the next available place in the array rather than at the end © 2004 Pearson Addison-Wesley. All rights reserved 7-231 Stacks • The java.util package contains a Stack class • Like ArrayList operations, the Stack operations operate on Object references • See Decode.java (page 623) © 2004 Pearson Addison-Wesley. All rights reserved 7-232 Outline Collections and Data Structures Dynamic Representations Queues and Stacks Trees and Graphs The Java Collections API © 2004 Pearson Addison-Wesley. All rights reserved 7-233 Trees • A tree is a non-linear data structure that consists of a root node and potentially many levels of additional nodes that form a hierarchy • Nodes that have no children are called leaf nodes • Nodes except for the root and leaf nodes are called internal nodes • In a general tree, each node can have many child nodes © 2004 Pearson Addison-Wesley. All rights reserved 7-234 Binary Trees • In a binary tree, each node can have no more than two child nodes • A binary tree can be defined recursively. Either it is empty (the base case) or it consists of a root and two subtrees, each of which is a binary tree • Trees are typically are represented using references as dynamic links, though it is possible to use fixed representations like arrays • For binary trees, this requires storing only two links per node to the left and right child © 2004 Pearson Addison-Wesley. All rights reserved 7-235 Graphs • A graph is a non-linear structure • Unlike a tree or binary tree, a graph does not have a root • Any node in a graph can be connected to any other node by an edge • Analogy: the highway system connecting cities on a map © 2004 Pearson Addison-Wesley. All rights reserved 7-236 Digraphs • In a directed graph or digraph, each edge has a specific direction. • Edges with direction sometimes are called arcs • Analogy: airline flights between airports © 2004 Pearson Addison-Wesley. All rights reserved 7-237 Representing Graphs • Both graphs and digraphs can be represented using dynamic links or using arrays. • As always, the representation should facilitate the intended operations and make them convenient to implement © 2004 Pearson Addison-Wesley. All rights reserved 7-238 Outline Collections and Data Structures Dynamic Representations Queues and Stacks Trees and Graphs The Java Collections API © 2004 Pearson Addison-Wesley. All rights reserved 7-239 Collection Classes • The Java standard library contains several classes that represent collections, often referred to as the Java Collections API • Their underlying implementation is implied in the class names such as ArrayList and LinkedList • Several interfaces are used to define operations on the collections, such as List, Set, SortedSet, Map, and SortedMap © 2004 Pearson Addison-Wesley. All rights reserved 7-240 Generics • As mentioned in Chapter 7, Java supports generic types, which are useful when defining collections • A class can be defined to operate on a generic data type which is specified when the class is instantiated: LinkedList<Book> myList = new LinkedList<Book>(); • By specifying the type stored in a collection, only objects of that type can be added to it • Furthermore, when an object is removed, its type is already established © 2004 Pearson Addison-Wesley. All rights reserved 7-241 Summary • Chapter 12 has focused on: the concept of a collection separating the interface from the implementation dynamic data structures linked lists queues and stacks trees and graphs generics © 2004 Pearson Addison-Wesley. All rights reserved 7-242