Optional Methods in Java Interface
In order to compile an implementing (non abstract) class for an interface - all methods must be implemented.
However, if we think of a method that its implementation is a simple exception throw as a 'non implemented' (like some methods in the Collection
interface), then the Collection
interface is the exception in this case, not the regular case. Usually, implementing class should (and will) implement all methods.
The "optional" in collection means that the implementing class doesn't have to 'implement' (according to the terminology above) it, and it will just throw NotSupportedException
).
A good example- add()
method for immutable collections - the concrete will just implement a method that does nothing but throwing NotSupportedException
In the case of Collection
it is done to prevent messy inheritence trees, that will make programmers miserable - but for most cases, this paradigm is not advised, and should be avoided if possible.
Update:
As of java 8, a default method was introduced.
That means, an interface can define a method - including its implementation.
This was added in order to allow adding functionality to interfaces, while still supporting backward compatability for pieces of code that does not need the new functionality.
Note that the method is still implemented by all classes that declare it, but using the interface's definition.
An interface in Java just declares the contract for implementing classes. All methods in that interface must be implemented, but the implementing classes are free to leave them unimplemented, viz., blank. As a contrived example,
interface Foo {
void doSomething();
void doSomethingElse();
}
class MyClass implements Foo {
public void doSomething() {
/* All of my code goes here */
}
public void doSomethingElse() {
// I leave this unimplemented
}
}
Now I have left doSomethingElse()
unimplemented, leaving it free for my subclasses to implement. That is optional.
class SubClass extends MyClass {
@Override
public void doSomethingElse() {
// Here's my implementation.
}
}
However, if you're talking about Collection interfaces, as others have said, they are an exception. If certain methods are left unimplemented and you call those, they may throw UnsupportedOperationException
exceptions.
There seems to be an awful lot of confusion in the answers here.
The Java language requires that every method in an interface is implemented by every implementation of that interface. Period. There are no exceptions to this rule. To say "Collections are an exception" suggests a very fuzzy understanding of what's really going on here.
It's important to realize that there are sort of two levels of conforming to an interface:
What the Java language can check. This pretty much just boils down to: is there some implementation for each of the methods?
Actually fulfilling the contract. That is, does the implementation do what the documentation in the interface says it should?
Well written interfaces will include documentation explaining exactly what is expected from implementations. Your compiler can't check this for you. You need to read the docs, and do what they say. If you don't do what the contract says then you'll have an implementation of the interface as far as the compiler is concerned, but it will be a defective/invalid implementation.
When designing the Collections API Joshua Bloch decided that instead of having very fine-grained interfaces to distinguish between different variants of collections (eg: readable, writable, random-access, etc.) he'd only have very coarse set of interfaces, primarily
Collection
, List
, Set
and Map
, and then document certain operations as "optional". This was to avoid the combinatorial explosion that would result from fine-grained interfaces. From the Java Collections API Design FAQ:
To illustrate the problem in gory detail, suppose you want to add the notion of modifiability to the Hierarchy. You need four new interfaces: ModifiableCollection, ModifiableSet, ModifiableList, and ModifiableMap. What was previously a simple hierarchy is now a messy heterarchy. Also, you need a new Iterator interface for use with unmodifiable Collections, that does not contain the remove operation. Now can you do away with UnsupportedOperationException? Unfortunately not.
Consider arrays. They implement most of the List operations, but not remove and add. They are "fixed-size" Lists. If you want to capture this notion in the hierarchy, you have to add two new interfaces: VariableSizeList and VariableSizeMap. You don't have to add VariableSizeCollection and VariableSizeSet, because they'd be identical to ModifiableCollection and ModifiableSet, but you might choose to add them anyway for consistency's sake. Also, you need a new variety of ListIterator that doesn't support the add and remove operations, to go along with unmodifiable List. Now we're up to ten or twelve interfaces, plus two new Iterator interfaces, instead of our original four. Are we done? No.
Consider logs (such as error logs, audit logs and journals for recoverable data objects). They are natural append-only sequences, that support all of the List operations except for remove and set (replace). They require a new core interface, and a new iterator.
And what about immutable Collections, as opposed to unmodifiable ones? (i.e., Collections that cannot be changed by the client AND will never change for any other reason). Many argue that this is the most important distinction of all, because it allows multiple threads to access a collection concurrently without the need for synchronization. Adding this support to the type hierarchy requires four more interfaces.
Now we're up to twenty or so interfaces and five iterators, and it's almost certain that there are still collections arising in practice that don't fit cleanly into any of the interfaces. For example, the collection-views returned by Map are natural delete-only collections. Also, there are collections that will reject certain elements on the basis of their value, so we still haven't done away with runtime exceptions.
When all was said and done, we felt that it was a sound engineering compromise to sidestep the whole issue by providing a very small set of core interfaces that can throw a runtime exception.
When methods in the Collections API are documented as being "optional operations", it does not mean that you can just leave the method implementation out in the implementation, nor does it mean you can use an empty method body (for one thing, many of them need to return a result). Rather, it means that a valid implementation choice (one that still conforms to the contract) is to throw an UnsupportedOperationException
.
Note that because UnsupportedOperationException
is a RuntimeException
you can throw it from any method implementation, as far as the compiler is concerned. For example, you could throw it from an implementation of Collection.size()
. However, such an implementation would violate the contract as the documentation for Collection.size()
does not say that this is permitted.
Aside: The approach used by Java's Collections API is somewhat controversial (probably less now than when it was first introduced, however). In a perfect world, interfaces would not have optional operations, and fine grained interfaces would instead be used. The problem is that Java supports neither inferred structural types or intersection types, which is why attempting to do things the "right way" ends up becoming extremely unwieldy in the case of collections.