Interfaces
An Interface is like a contract, it guarantees the preconditions required to produce the desired postconditions.
- Like an extreme case of an abstract class.
- Java does not support multiple inheritance– interfaces can be used as a means to implement their behaviour.
- Specifies a set of methods that any class that implements the interface must have.
- Contains method headings and constant definitions only.
- Contains no instance variables nor any complete method definitions.
- Must be declared as public.
- Interfaces are also a type.
- A method may be written with a parameter of an interface type.
- That parameter will accept as an argument any class that implements the interface.
- Use the
interface
keyword instead ofclass
within its definition. - Methods implementing it must use the
implements
modifier.- A method (including abstract methods) can implement multiple interfaces.
- If multiple interfaces are implemented they can’t have conflicting method definitions.
- Interfaces may be also be derived by including the
extends
keyword in its definition.
Comparable Interface
- Allows collections that implement the interface to be automatically sorted by
Collections.sort
orArrays.sort
. - Objects that implement this interface can be used as keys in a map or set without the need to specify a comparator.
- Only has one method heading that must be implemented:
public int compareTo (Object other)
- Same kind of behavior as C’s
strcmp
;compareTo
must return…- A negative if the calling object comes before.
- Zero if the calling object is equal.
- A positive number if the calling object comes after.
- If the parameter
other
is not of the same type as the class being defined then aClassCastException
should be thrown.
Iterator Interface
public interface Iterator<E>
next
throwsNoSuchElementException
if the iteration has no more elements.- You probably don’t want to call
next
more than once per loop.
- You probably don’t want to call
- Implemented by all Collections.
Return | Method | Description |
---|---|---|
boolean | hasNext() |
Returns true if iterations has more elements. |
E | next() |
Returns the next element in the iteration. |
void | remove() |
Removes last element returned by iterator. |