Content deleted Content added
added the paragraph about unwanted inheritance of interfaces in Java. |
|||
Line 4:
One good example of a marker interface comes from the [[Java programming language]]. The ''[http://java.sun.com/j2se/1.4.2/docs/api/ Cloneable]'' interface should be implemented by a class if it fully supports the [http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#clone() Object.clone()] method. Every class in Java has the [http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html Object] class at the root of its inheritance hierarchy and so every object instantiated from any class ''has'' an associated clone() method. However, developers should only call clone() on objects of classes which implement the ''Clonable'' interface, as it indicates that the cloning functionality is actually supported in a proper manner.
Unfortunately there is a problem with this Java example, namely that in Java you cannot "unimplement" an interface. So if you subclass a class that implements Clonable, and then do something in your subclass that means it can't be cloned properly, your subclass will still be marked as a Clonable whether you want it or not. One way out is to throw an Exception (a [http://java.sun.com/j2se/1.4.2/docs/api/java/lang/CloneNotSupportedException.html CloneNotSupportedException] is a good idea) in the clone() method, but then you are missing the whole point of the marker interface.
Still, this is generally a good idea, as subclasses usually ''do'' inherit behaviors from their parents and should inherit the marker interfaces as well.
[[Category:Software design patterns]]
|