Recent Posts

Meta

Notes on Java 6

If you’ve not caught up with what polymorphism is, you should check the previous entry on this series.

Java has a pretty ergonomic standard library (except when it’s not, as in the date and time APIs – Some work has been done in Java 8 to help improve them). You can, and maybe should, peruse the Java API javadocs to better acquaint yourself with the wealth that the platform offers.

One of the mechanisms leveraged in the Java API to achieve this ergonomy is the use of polymorphism through interface implementation. In case this hasn’t been cleared up, the relationship is this: the interface states some behavior should be implemented, and the class contains the implementation of the behavior while leveraging the particular scenario. If it’s still not clear, bear with me and read on: all should be clarified shortly.

Some interfaces and what they mean:

Runnable

A tiny interface – only specifies the “void run()” method. Basically specifies what should get done when a thread is starter with a particular object.

Comparable<T>

This interface defines one single method: “int compareTo(T o)”. That “T” is a reference to the class which implements the interface, so every implementing class should be able to compareTo(anObjectOfTheSameClass); the use of generics is a topic for the future.

This is a simple and useful interface. The return value is interpreted as a particular meaning (this goes first, at the same point, or after the other object in its natural order). If you were to write an algorithm to order any kind of data, then you could make it order Comparable-compliant classes, and not need to know the details of any of them to write useful code. In fact, it’s both trivial and included in Java – you only need to set up a class implementing the List<T> interface filled with Comparable<T> objects, and invoke Collections.sort on the list.

In other languages, it is possible to recreate this effect by overloading the comparison operators in your composite type.

AutoCloseable

This one specifies the “void close()” method; it should free all used resources and do general clean-up. This is necessary for the try with resource construct introduced in Java 7.

Closeable

This one specifies the “void close()” method; if you think this is a dejà-vu, rest assured that it isn’t. There’s a difference between this and the previous interface; Closeable is derived from AutoCloseable. Look at the one, then the other, until you spot it.

Hint: the intent behind deriving a type from another is to execute a conceptually equivalent task in a specific setting.