A colleague sent me this today, which I will shamelessly steal and blog here: [source:java]
public class SuperDuper {
public static void main(String[] args) {
Class c = B.class;
while (c != null) {
System.err.println(c.getName());
c = c.getSuperclass();
}
}
}</p>
interface A { }
interface B extends A { }
[/source]
Ok, puzzle through it…what does this print? No fair cheating.
You might naively expect this to print B then A. But instead you will see just B. You will note that the javadoc says that for an interface, getSuperclass() returns null.
This of course makes perfect sense as multiple inheritance is allowed for interfaces in Java and thus there is no one “super-interface” but 0 or more. I’ve leveraged this in the past to create a composite interface that merges simplified “view” interfaces presented by an object in different roles. For example: [source:java]
public interface SetReader {
boolean contains(Object o);
Iterator iterator();
}
public interface SetWriter {
void add(Object o);
}
public interface Set extends SetReader, SetWriter {}
[/source]
You can then up-cast to either SetReader or SetWriter when you want the Set to only play the reader/writer role in some component.
If you do need to get information on what interfaces an interface extends, you’ll note they are returned from getInterfaces() in the order defined in the extends clause.