Toronto CSC 148 - Interfaces and Abstract Classes

Unformatted text preview:

INTERFACES ANDABSTRACT CLASSES1Interfaces for defining ADTsWhile studying the Queue ADT, we saw:• How to define an interface using the keyword interface.• How to write a class that implements an interface using the keywordimplements.But we could have just written classes ArrayQueue and CircularQueue, withoutdefining interface Queue.So why bother to have the interface in addition to the classes?2Advantages of separating an ADT’s interfacefrom its implementation1. Easier to change implementations.Recall our interface Queue for the Queue ADT, and our two implementationsof it: ArrayQueue and CircularQueue.Change this program to use a CircularQueue:public class QueueTest {public static void fill(Queue q, int n) {for (int i=0; i != n; i++) {q.enqueue(new Integer(i));}}public static void main(String[] args) {Queue q = new ArrayQueue(15);fill(q, 15);}}3How hard would it be if instead we had classes ArrayQueue and CircularQueuebut no interface Queue above them?The difference would be more dramatic with a large program.It would be even worse if classes ArrayQueue and CircularQueue didn’t useexactly the same method headers. The interface enforces that.2. Easier to use two implementations simultaneously.Example:Queue q1 = new ArrayQueue(15);Queue q2 = new CircularQueue(22);fill(q1, 15);fill(q2, 15);4Some rules about interfaces• A Java interface may only contain– instance method headers, and– constants (implicitly static and final).• All these members are implicitly public.• You cannot instantiate (construct instances of) an interface.• If a class implements an interface, it must provide bodies for all methods— otherwise it must be an “abstract” class (more later).• An interface can extend other interfaces.• A class can extend only one class, but it can implement many interfaces.5QuestionsWhy would it be pointless to:• Allow members of an interface to be private?• Create an instance of an interface?Would interfaces be useful if variables in Java didn’t need to have their typesdeclared?6Interfaces for general codeSuppose we want to be able to sort arrays of fractions, students, integers,cars, etc.Once we’ve chosen a sorting algorithm, the logic for sorting is the same nomatter what the objects are. So we certainly don’t want to write a separatesort method for each kind of object!We want a general method to sort any array of Objects.public static void sort(Object[] a) {// Loop around and put things in order.}But now we’re stuck: To put things in order, we have to be able to compareany two and decide which goes first. Object doesn’t provide any method fordoing this.7The problemWe want to provide a sorting service, but we need our subscribers to ensurethat they give us only objects that have a particular property: they must becomparable.An interface can help express this.The comparable idea is so useful that it is in the Java API.Interface ComparableComparable is part of the Java API. It contains only one method:public interface Comparable<T> {/*** Compares this object with o for order. Returns* a negative integer, zero, or a positive integer* as this object is less than, equal to, or* greater than o.*/int compareTo(T o);}8A service that requires a ComparableWe can now write sort():public static void sort(Comparable[] a) {// Loop around and put things in order.// Use compareTo() to decide on the order:if (a[i].compareTo(a[j]) < 0) ...// Other details are unimportant here.}Expecting a class to implement Comparable (so that it can be sorted) is notonerous because:• This requires only that it have a compareTo() method, the weakest re-quirement that will make sorting possible.• As we mentioned, a class can implement as many interfaces as needed(unlike extending classes), so a class can subscribe to many services.Although Comparable allows a generic type parameter T, if you omit “<T>” asin the code above, things still work.9Using the sort serviceString implements Comparable, so we can sort Strings with our method:String[] list = new String[10];// Fill in list...:sort(list);// list is sorted!Two nice features:• Method sort is general: it can handle anything that is sortable, not justStrings.Many Java API classes implement Comparable, and any class of your owndesign can be made comparable. (How?)• We can write sort() without knowing anything about the particularComparable objects that will be passed in.We can write lots of other methods that use the Comparable interface. Ideas?10Properties of Objects vs of ClassesConsider the following code fragment:Comparable[] list = new Comparable[2];list[0] = "Hello";list[1] = new Integer(57);sort(list);What do you think happens?Being comparable is really a property of a set of objects. Strings are Comparableto each other. This is called “mutually comparable” in the Java API.One reason why generics were introduced in Java 1.5 was to provide a safeway to specify mutual comparability and similar concepts.Our convention in this course is to assume that objects specified to beComparable are mutually comparable, unless we say otherwiseQuestion: Does equals(Object) make sense for objects of two differentclasses?11A Design PatternSuppose we want to go through the elements contained in an object, doingsomething with each one.Your first thought: go through by index.// LinkedLists have elements, like Vector or an array.LinkedList list = new LinkedList();list.add(...);...for (int i = 0; i != list.size(); ++i) {... do something with list.get(i) ...}For many data structures (LinkedList is one of them), getting the elementat a particular index isn’t very fast, but moving from one element to the nextis fast.12An Index with MemoryTo get the ith element of a LinkedList, the list has to look through all theelements before it, as we learned in the “Linked Data Structures” section ofthe course.For example, list.get(20) takes twice as long as list.get(10).But if the LinkedList could “remember where” the ith element is it could getthe i + 1st very quickly.As we’ve already discussed, instead of having the collection remember wherethe last thing we asked for is, we use another object as a kind of “smart index”.This is the basis of the “iterator” approach that we introduced earlier.13Design PatternsAn iterator is an example of a “design pattern”.A design pattern is a solution to a common software design problem. It isa general, flexible template that can be applied in many different situations,and so it


View Full Document

Toronto CSC 148 - Interfaces and Abstract Classes

Download Interfaces and Abstract Classes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Interfaces and Abstract Classes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Interfaces and Abstract Classes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?