Java Interfaces used as types

Here are some notes I have made about using Java Interfaces as types, prompted by my initial confusion about the concept,  a discussion with Michele Bachler,  and reading this and this (thanks to both web sites and Michelle for helping to clarify this stuff).

A method which is specified to return an interface type can return an object of any type (class) that implements that interface.

So if an interface (e.g. Interface A) specifies a method signature in which the method should return an interface type (e.g. Interface B) , then any classes that implement  Interface A must provide a method which returns an object which implements Interface B. This returned object can be of any type, so long as it implements Interface B.

For example, from the Compendium code, the IServiceManager interface specifies

/**    Look for a free node service in the relevant cache, else create a new service, and return it.    **/

public INodeService getNodeService();

and this IServiceManager interface is implemented  by the ServiceManager class, e.g. via this method

public INodeService getNodeService() {

    String sName = “”;

    NodeService node = null; /** NodeService implements INodeService **/

    <snip>…Lots of code removed </snip>

    return node;  /** This is the node object which implements the INodeService  interface**/

}

This entry was posted in compendium and tagged . Bookmark the permalink.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>