I am neither a Java aficionado nor a Java guru, but I use it as a vehicle for teaching programming at an undergraduate level.

In this post, I describe a simple situation where the need for a self type arises in Java. I present a way of simulating a self type in Java, and also suggest that in this case, by changing the code slightly, one can avoid the need for a self type in the first place. None of these ideas is new, but perhaps they deserve to be more widely known.

The Java library offers a simple implementation of the subject/observer design pattern. It takes the form of an Observable class, which maintains a list of observers, and an Observer interface, which states (in short) that an observer must be able to receive a message.

A subject is essentially a publisher

In the subject/observer design pattern, an observer is supposed to be notified only when the state of the subject changes. Java’s Observable class provides a Boolean field called changed, together with getter and setter methods. The method notifyObservers does nothing unless changed is set, and clears it. This relatively simple logic is independent of the point that interests me, so I will omit it from this discussion.

As a result of this omission, the subject/observer pattern degenerates and becomes essentially a publisher/subscriber pattern, where a subject can decide at any time to send a message to all of its observers.

A key point of interest, though, is that the subject sends itself as the message (or as part of the message).

Java’s Observer and Observable are not generic

Have a look at Java’s Observer interface. The update method expects two arguments: the subject that sends the message, and the message itself.