Java Puzzler: interface super classes

7

A colleague sent me this today, which I will shamelessly steal and blog here:

public class SuperDuper {
public static void main(String[] args) {
Class c = B.class;
while (c != null) {
System.err.println(c.getName());
c = c.getSuperclass();
}
}
}

interface A { }
interface B extends A { }

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:

public interface SetReader {
boolean contains(Object o);
Iterator iterator();
}

public interface SetWriter {
void add(Object o);
}

public interface Set extends SetReader, SetWriter {}

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.

Comments

7 Responses to “Java Puzzler: interface super classes”
  1. kodeninja says:

    Alex, the ‘class’ (keyword… oops) variable in the SuperDuper class should actually be something else.

    ‘clazz’, probably :)

  2. Alex says:

    Crap, thank you. That’s what I get for taking working code and refactoring it in the blog editor! Changed back to c.

  3. Casper Bang says:

    Variable name of clazz is usually used in Java from what I’ve seen.

    For once, consistent behavior between Java an .NET, not so with this next one (seems like you are collecting puzzlers these days?!):

    System.out.println( max(0.0, -1.0, -2.0) );

    public static double max(double… candidates)
    {
    assert(candidates.length > 0);
    double knownMaxValue = Double.MIN_VALUE;
    for(double candidate : candidates)
    if(candidate > knownMaxValue)
    knownMaxValue = candidate;
    return knownMaxValue;
    }

  4. That would be upcasting, not downcasting.

  5. Alex says:

    @Casper: I’m not a fan of “clazz”, I’ll stick with c. Your puzzlers not too confusing if you know that Double.MIN_VALUE is smallest positive non-zero value. Java 6 added a Double.MIN_NORMAL as the smallest possible Double value. Float’s the same.

    @Ricky: Spot on.

Trackbacks

Check out what others are saying about this post...
  1. [...] Alex Miller – Java Puzzler: interface super classes [...]

  2. [...] Alex Miller – Java Puzzler: interface super classes [...]



Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!