cs230 Lecture Notes Week 8, Thursday For Monday you should work on hw07, which is due next Tuesday in lab. Quiz 7 Solutions ---------------- If you are not sure whether an object can be typecast to a given type, you can check: Class c = Comparable.class; boolean flag = c.isAssignableFrom (o.getClass()); Today's topics -------------- 1) process objects (from notes14.txt) 2) abstract classes 3) hw07 introduction Abstract class (a.k.a interface) -------------------------------- An abstract class is a set of classes. The abstract class specified the membership requirements. Any class that meets the requirements can be in the club. Example: Comparable is an abstract class that includes Integer, Double, or any other class that provides a compareTo method. How do you join the club? You have to declare that you "implement" the abstract class. public class Golfer implements Comparable { String name; int score; } And then provide what you have to provide: public int compareTo (Object obj) { Golfer that = (Golfer) obj; int a = this.score; int b = that.score; // for golfers, low is good! if (ab) return -1; return 0; } Notice that the parameter is an Object, not a Comparable. At compile time, the compiler checks whether you have met the requirements. If not, it will tell you that the new class is still abstract! (not fully specified) A class can be a member of several clubs at the same time. Data structure view ------------------- Why is this useful? It makes it possible to write a generic data structure, but give it the ability to invoke at least some methods on the items. Example: PriorityQueue Write everything in terms of comparable. You can do anything to a comparable that you can do to an Object, PLUS you can invoke any methods specified in the abstract class definition. public PriorityQueue () { array = new Comparable [16]; index = 0; } public Comparable remove () { if (index == 0) return null; int maxIndex = 0; // find the item with the highest priority for (int i=1; i 0) { maxIndex = i; } } Comparable result = array[maxIndex]; // move the last item into the empty slot index--; array[maxIndex] = array[index]; return result; } Client view ----------- To make a Comparable object, you instantiate one of the classes that belong to the club PriorityQueue pq = new PriorityQueue (); Integer item = new Integer (17); pq.insert (item); When you get the thing back, you have to cast it back to what it was: item = (Integer) pq.remove (); As usual, there is an information barrier between the client and the provider. The client knows the details (what type the items are); the provider knows as little as possible (only that the items are Comparable).