Share

From this page you can share Referencing Subtypes in Generics to a social bookmarking site or email a link to the page.
Social WebE-mail
Enter multiple addresses on separate lines or separate them with commas.
Referencing Subtypes in Generics
(Your Name) has forwarded a page to you from Ajaxonomy
(Your Name) thought you would like to see this page from the Ajaxonomy web site.

Referencing Subtypes in Generics

Tagged:  

I ran into a problem recently while programming in Java where I wanted to define an interface method that returned a generic type which was tied to the type of the implementing class. If that sounds a little long-winded, let me give an example...

Let's say we have a Thing interface that defines a method for getting a type token, public Class<T> getType(). The Thing interface has several implementers, MyThing, YourThing, HisThing, HerThing, and so on. How does one make sure that T is the right subtype in the interface, which has no "knowledge" of its implementers (the same could be said of any base class and subclass as well)? Actually, the answer was sitting right under my nose in the core java libraries themselves, in the Enum class, whose declaration looks like this:

public abstract class Enum<E extends Enum<E>>

The E generic type looks a little confusing at first, like a kind of recursive definition. But when you think about it, it makes perfect sense: E is a subclass of an Enum type that is generified with the type--what else?--E. And E must be the appropriate subtype in any implementing class. So getting back to our little example, I could now retrofit my Thing interface to look like:

public interface Thing<T extends Thing<T>> {
     public Class<T> getType();
}

Any implementer now simply references itself in the generic type declaration:

public class MyThing implements Thing<MyThing> {
     public Class<MyThing> getType() { ... }
}

Most programmers prefer to think of generics only in the context of collections. But this provides a good example of how generics can establish type relationships in ways that are not possible in more traditional OOP methodology.