Download presentation
Presentation is loading. Please wait.
Published byBlanche Wiggins Modified over 9 years ago
1
CS 151: Object-Oriented Design September 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak www.cs.sjsu.edu/~mak
2
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 2 Assignment #2 Review What are the primary classes? Game Controller Human Player Computer Player Typed in after a prompt Graphical user interface (press the rock, paper, or scissors button) Randomly Smart algorithm etc. Can vary. Must encapsulate! Ways to input the human player’s throw Ways to calculate the computer player’s throw
3
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 3 Assignment #2 Review Encapsulate calculating the computer’s throw. ThrowCalculator calculateThrow(): Throw ComputerPlayer RandomThrow calculateThrow(): Throw SmartThrow calculateThrow(): Throw GeniusThrow calculateThrow(): Throw Abstract superclass Calendar Gregorian Calendar Lunar Calendar Recall:
4
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 4 Assignment #2 Review Preserve your design flexibility! What’s wrong with this code? RandomThrow randomThrow = new RandomThrow(...); Throw t = randomThrow.calculateThrow(...); Use the Factory Method Design Pattern and code to the interface. ThrowCalculator calc = ThrowCalculator.makeCalculator(type,...); Throw t = calc.calculateThrow(...); ThrowCalculator calculateThrow(): Throw ComputerPlayer RandomThrow calculateThrow(): Throw In this example, coding to the interface means coding to the superclass ThrowCalculator.
5
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 5 Quiz #2 2013Sept26
6
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 6 Feed Our Pets Suppose you have an array animals of animal objects: Animal MammalFishBird LionDogPiranhaGoldfishParrotHummingbird «interface» HouseholdPet «interface» Biter Animal animals[];
7
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 7 Feed Our Pets Recall the definition of interface HouseholdPet : How we find and feed all our pets that are in array animals ? public interface HouseholdPet { void feed(Food f); } for (int i = 0; i < animals.length; i++) { if ((animals[i] != null) && (animals[i] instanceof HouseholdPet)) { HouseholdPet pet = (HouseholdPet) animals[i]; Food f = Food.make(pet); // factory method pet.feed(f); } }
8
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 8 Feed Our Pets Instead of: you can write: HouseholdPet pet = (HouseholdPet) animals[i]; pet.feed(f); ((HouseholdPet) animals[i]).feed(f); The first way may be easier to write and read! _
9
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 9 Marker Interfaces What if an interface type doesn’t declare anything? Suppose public interface Biter { // nothing! } A marker interface is an empty interface that serves to “tag” the classes that implement it. Use the instanceof operator to see which objects are from a tagged class. _
10
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 10 Avoid Biters! Example of how to use a marker interface: for (int i = 0; i < animals.length; i++) { if ((animals[i] != null) && (animals[i] instanceof Biter)) { // Code that does something // with animals that are biters. // // The code doesn’t call any // Biter methods (because // there aren’t any). } Animal animals[];
11
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 11 Polymorphism The code of method showMessageDialog() needs the width of the icon that was passed in as a parameter. Interface Icon declares a getIconWidth() method. public static void showMessageDialog(Component parent, Object message, String title, int messageType, Icon anIcon) public interface Icon { int getIconWidth(); int getIconHeight(); void paintIcon(Component c, Graphics g, int x, int y); }
12
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 12 Polymorphism Any object passed as the anIcon parameter be must be instantiated from a class that implements the Icon interface. Method showMessageDialog() doesn’t care whether the parameter is an instance of ImageIcon or MarsIcon, or any other object, as long as the object was instantiated from a class that implements the Icon interface. Method showMessageDialog() calls method getIconWidth() on the parameter. Implementations of method getIconWidth() may all be different with nothing in common other than the name and return type. public static void showMessageDialog(Component parent, Object message, String title, int messageType, Icon anIcon)
13
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 13 Polymorphism The feed() method of class Dog and the feed() method of class Goldfish may have very different implementations. public interface HouseholdPet { void feed(Food f); } public class Dog extends Mammal implements HouseholdPet { public void feed(Food f) { // code to feed a dog }... } public class Goldfish extends Fish implements HouseholdPet { public void feed(Food f) { // code to feed a goldfish }... } Recall our interface HouseholdPet.
14
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 14 Polymorphism Even though the feed() method of each HouseholdPet object may be different, we can call each feed() method the same way. Our code is flexible: It doesn’t matter which Animal it is, as long as it’s a HouseholdPet. for (int i = 0; i < animals.length; i++) { if ((animals[i] != null) && (animals[i] instanceof HouseholdPet)) { HouseholdPet pet = (HouseholdPet) animals[i]; Food f = Food.make(pet); // factory method pet.feed(f); } }
15
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 15 Polymorphism Polymorphism: The ability to appear in many forms. In Java, polymorphism is The ability of a variable to automatically change behavior according to what object it refers to. The ability to automatically select the appropriate method M for a particular object, when there are multiple objects of different classes that all implement an interface that declares method M. there are multiple objects of different subclasses of a superclass that declares method M. _
16
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 16 Advantages of Polymorphism Loose coupling Class JOptionPane uses the Icon interface but is decoupled from the MarsIcon or the ImageIcon classes. Extensibility You can develop new types of icon objects, as long as their classes implement the Icon interface.
17
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 17 The Comparable Interface Type The Java Collections class has a static sort() method that can sort any array list: The list can contain objects of an arbitrary class, such as Animal. How can the sort() method sort the list? How can it determine whether one object in the list is greater than, less than, or equal to another object? Answer: The class of the objects in the list must implement the Comparable interface. Collections.sort(list); ArrayList aList;
18
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 18 The Comparable Interface Type, cont’d Suppose class Animal implements interface Comparable : public interface Comparable { int compareTo(T other); } public class Animal implements Comparable {... }
19
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 19 The Comparable Interface Type, cont’d Now class Animal must implement the interface’s compareTo() method. The call object1.compareTo(object2) is expected to return: a negative value if object1 should come before object2 0 if both object1 and object2 are equal a positive value if object1 should come after object2 public interface Comparable { int compareTo(T other); }
20
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 20 The Comparable Interface Type, cont’d Let’s compare animals by their weights: public class Animal implements Comparable { int weight; int height; public int compareTo(Animal other) { if (weight < other.weight) return -1; if (weight > other.weight) return +1; return 0; }... } Of course, all the animal subclasses inherit the weight field and the compareTo() method.
21
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 21 The Comparator Interface Type Suppose we might want to compare not just by the animal’s weights, but also by their heights, or perhaps by some other field. So the comparison method can vary! Therefore, we must... ?? A second form of method Collections.sort() takes two parameters: 1. the array list to sort 2. an object of a class that implements the Comparator interface public interface Comparator { int compare(T first, T second); }
22
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 22 The Comparator Interface Type To sort an Animal array list aList by height: public class AnimalComparatorByHeight implements Comparator { public int compare(Animal animal1, Animal animal2) { if (animal1.height < animal2.height) return -1; if (animal1.height > animal2.height) return +1; return 0; } Comparator comp = new AnimalComparatorByHeight(); Collections.sort(aList, comp);
23
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 23 The Comparator Interface Type Let the sort be ascending or descending: public class AnimalComparatorByHeight implements Comparator { private int dir; public AnimalComparatorByHeight(boolean ascending) { dir = ascending ? 1 : -1; } public int compare(Animal animal1, Animal animal2) { if (animal1.height < animal2.height) return -1*dir; if (animal1.height > animal2.height) return +1*dir; return 0; }
24
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 24 The Comparator Interface Type Now to sort the Animal array list aList in descending order: Comparator comp = new AnimalComparatorByHeight(false); Collections.sort(aList, comp); We can shorten the above code. Variable comp really isn’t necessary if we don’t use it again. Collections.sort(aList, new AnimalComparatorByHeight(false)); ArrayList aList;
25
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 25 Anonymous Classes public class AnimalComparatorByHeight implements Comparator { public int compare(Animal animal1, Animal animal2) { if (animal1.height < animal2.height) return -1; if (animal1.height > animal2.height) return +1; return 0; } Comparator comp = new AnimalComparatorByHeight(); Collections.sort(aList, comp);
26
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 26 Anonymous Classes Notice that in our program, after we declare class AnimalComparatorByHeight, we use the class in only one statement: Comparator comp = new AnimalComparatorByHeight(); We can shorten our code even further by not giving the class a name in a separate class definition. Define the body of the class only when it’s used. Make it an anonymous class. _
27
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 27 Anonymous Classes Comparator comp = new Comparator () { public int compare(Animal animal1, Animal animal2) { if (animal1.height < animal2.height) return -1; if (animal1.height > animal2.height) return +1; return 0; } }; Collections.sort(aList, comp); Interface that the class implements Note the semicolon Comparator comp = new AnimalComparatorByHeight(); Collections.sort(aList, comp);
28
SJSU Dept. of Computer Science Fall 2013: September 26 CS 151: Object-Oriented Design © R. Mak 28 Anonymous Classes We can even get rid of variable comp : Collections.sort(aList, new Comparator () { public int compare(Animal animal1, Animal animal2) { if (animal1.height < animal2.height) return -1; if (animal1.height > animal2.height) return +1; return 0; } }); Note the closing parenthesis Collections.sort(aList, comp);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.