i try to simplify with a pragmatic example:
////////////////////
//VERY(!) simplified, real forums are more complex.
public interface ForumActions{
/** @throws UserDisallowedException, email is not allowed to post. */
Thread startThread(String email, String threadName, String description)
throws UserDisallowedException;
/** @throws UserDisallowedException, email is not allowed to comment. */
void commentThread(String email, Thread thread, String comment)
throws UserDisallowedException;
}
///////////////////////////
//IMPLEMENTATION 1
public class StackOverflowForum implements ForumActions{
/**
* @param email Email of poster, which must have been registered before.
*
* @throws UserDisallowedException The mail address is not registered
*/
public Thread startThread(String email, String threadName, String description)
throws UserDisallowedException {
if(isNotRegistered(email))
throw new UserDisallowedException(...);
...
return thread;
}
}
...
}
///////////////////////////
//IMPLEMENTATION 2
public class JavaRanchForum implements ForumActions{
/**
* @param email Email of poster, which mustn't have exceeded a posting-limit per day.
* This way we protect against spammers.
*
* @throws UserDisallowedException, the mail was identified as a spamming origin.
* is mandatory for posting threads.
*/
public Thread startThread(String email, String threadName, String description)
throws UserDisallowedException {
if(isSpammer(email))
throw new UserDisallowedException(...);
...
return thread;
}
}
...
}
as you see the interface itself is a contract, which is a combination of:
- 'how' do i call it: e.g. what name does it have, what types are involved. syntax.
- 'what' does it do: what is the effect of using the interface. this is documented either by good naming and/or javadoc.
Above classes are the implementations of the interface which have to follow its contract.
Therefore interfaces shouldn't be too strict about 'how' the implementations have to implement the contract (in my case: why is the user not allowed to post/comment -> spammer vs. not-registered).
as said, very simplified example and by far NOT a complete reference for interfaces.
for very funny and practical examples about interfaces (and general object orientation) have a look at head first design patterns. it is nice for novices and also for professionals