Core Java: marker interface

A marker or tagging interface is an interphase with no methods. It can be created by ANYBODY. the purpose of these interfaces is to create a special type of Object, in such a way that you are restricting the classes that can be cast to it without placing ANY restrictions on the exported methods that must be provided. It mostly indicates that a class should or should not be considered an acceptable class for a certain operation.

Some examples are:

Serializable: This is used to indicate that an object may be serialized for persistance purposes. It has no methods. The writeObject and readObject methods are actually not part of the interface, but rather part of the serialization process, and help determine how to serialize an object. hence, when using a design tool (like jBuilder), when you implement serializable, it automatically creates writeObject and readObject — But they are not necessary.

Cloneable: Every Object has a method clone(). But in order to call that method, a class must be marked as Cloneable. Thus, it is just another marking interface.

EventListener: EventListener is a tagging interface that is an important part of introspection in Java Beans. It is possible to use the Delegation Event design for events without implementing EventListener, but in order for the Java beans introspector to recognize the EventListener, it must be tagged by implementing java.util.EventListener.

And the list goes on…

Here’s an example where you could create youre own tagging interface:

let’s say you were modeling a department store. You have objects that represent all of the merchendise you can sell. Now, you have an initiative in the store that you will sell at least 70% American Made merchendise. Then you could create the interface

public interface AmericanMade {} 

and implement that on every object you sell that is made in America. Now, a customer come and wants to purchase only American Made products, so you show him a revised catalogue, like this:

for (Product product : allProducts) {
  if (product instanceof AmericanMade) {
    newList.add(product);
  }
} 

See, the whole point is that it creates a new type of merchendise, the AmericanMade, that can be distinguished from others, whether the product is Toilet Paper, T-Shirts, Motor Oil, or Golf Clubs. It does not define any properties or methods, though, because there is likely no difference between an american made golf club and an English golf club, except that buying one helps support the American economy, and the other hleps support the English economy.

Collected from Sun Java forums.

One thought on “Core Java: marker interface

  1. Can you please elaborate this example…
    Pls share the example like clonable interface where class which implements clonable interface can only call clone method else exception is thrown..

Leave a Reply

Your email address will not be published. Required fields are marked *