Recent Posts

Meta

Notes on Java 7

Remember when we talked about the two kind of relationship between concepts (aka blueprints, aka classes) in Java? One interface-based and another class-based? (Please, bear in mind that interfaces are blueprints-of-blueprints, which means they’re blueprints, too, just a special kind).

In any case, interface based relationships are peculiar. You may remember the notes on Java’s ergonomy and its relationship with existing interaces. If you don’t skim Notes on Java 6 to get a sense of where I’m going.

You may notice that some interfaces have a <T> up there? Let’s talk about that.

Interface based relationship is also called contract based relationship, because the interfaces basically state things that are guaranteed to be doable.

The <T> is another type of contract, this time guaranteeing not operations, but types. The “T” represents a type. Usage of this is called Generics programming.

When you declare a class to include the generic type <T>, you can then refer to it inside, to receive parameters of the same type T. This gets substituted by whatever is used by the programmer, lending type safety.

A<String> a = new A<>(); // before Java 7 you had to type <String> twice.
a.setParameter("someString");

all will be well, but if you do this:

A a = new A<String>();
a.setParameter(25);

it will fail at compile time.

Which is good. The possibilities are many, but this ensures that a particular composite type is coherent.

A special case for generics is when you want to make sure you are working with a type that has a particular relationship to another, known type, be it above (general) in the hierarchy or below (specialized).

For these cases, the special, wildcard argument “?” is used, like this: