Class 17
Homework
Print out and complete this page.
Interfaces
We have one last topic to cover regarding inheritance: Interfaces. First, though, a side note. Many Object-Oriented languages allow for multiple inheritance, in which a single subclass can have multiple superclasses. The benefits are probably obvious to you, but the drawbacks are significant, as well; what if both superclasses have methods called the same thing? Or what if Class B extends Class A, and then Class C extends both A and B? In short, things get dirty, quickly. Java just avoids this; no muliple inheritance. However, it can get some of the same benefits with interfaces.
The brief definition is that interfaces specify behavior for a class, in a way very similar to abstract methods in an abstract class. If a class extends an abstract class, it must implement the abstract methods. Similarly, if a class implements an interface, it must implement all the methods. An example interface, Comparable, follows:
public interface Comparable {
public int compareTo(Object o);
}
Interfaces can have as many of these method signatures as they like, but NONE of them can actually have definitions.
So, now, if we have a class AClass, which implements Comparable, it MUST implement the method compareTo()
public class AClass implements Comparable {
//Other AClass stuff
public int compareTo(Object o) {
//implementation
}
}
If AClass implemented Comparable, without implementing that method, then it wouldn't compile!
So What?
Suppose you have an array of objects of some type, and you want to sort it. You could write a new sort function that handles an array of that type, but you would have to rewrite it for each new type of objects. However, if we know the objects in question have a method that will tell me if array[i] goes before or after array[k] (called, oh, say, compareTo), then the type doesn't matter. ANY object with a compareTo method can be sorted by our function!
So, we have to have some way of guaranteeing that our objects will have this function; we can do this by limiting the input array to types that have implemented Comparable. If they've implemented Comparable, then they MUST have implemented compareTo(), and our function will work.
Just as you can create pointers to superclasses using polymorphism, you can also make pointers to interfaces:
public Object[] sort(Object[] a) {
Comparable[] b = new Comparable[a.length];
for (int i = 0; i < a.length; i++)
b[i]=a[i]; // Implicit cast
//finish sorting using compareTo() for guidance
}
There is, in fact, a function that does exactly this. Array.sort() will take in an array of Objects that have implemented Comparable, and sort them. If they don't implement Comparable, no sorting allowed.