Using interfaces

Interfaces are a good way to define rules by which objects interact. If one object likes to communicate with another it has to have a way to determine whether or not that other object 'understands'. If an object can determine from which class another object was instantiated, it can expect or not expect certain methods being present.

If an object is to implement an interface it has to implement all methods the particular interface defines. How the methods are implemented, i.e. which code they actually hold, is up to the implementing object. A single object can implement many interfaces.

Example: SHTMLAction

In application SimplyHTML this is demonstrated by interface SHTMLAction.

In the process of dynamic menu creation method createMenu adds an SHTMLMenuListener to each menu. SHTMLMenuListener is used to update all actions to reflect the up to date enabled state prior to selection of a menu. To be able to do this, SHTMLMenuListener must determine, whether or not an action that is to be updated, actually has a method to update its enabled state.

Interface SHTMLAction is defined so that SHTMLMenuListener can do that. SHTMLMenuListener checks if an action is of instance SHTMLAction which it only would be if it implements interface SHTMLAction. Only if an action is an instance of SHTMLAction, its update method is called, because otherwise SHTMLMenuListener can not be sure if there is a method update in the particular action object.

Another advantage of the interface methodology is that objects of any class can implement interface SHTMLAction so that an object instantiated from class SHTMLUndoAction can be an instance of SHTMLUndoAction and an instance of SHTMLAction too even if SHTMLAction is not a superclass according to the class hierarchy of SHTMLUndoAction .