Search code examples
javaabstract-methods

How a method in Java can be both abstract and declared as "optional"?


For example in Collection interface, we have: From Java Documentation - Collection Interface

If the method is optional it means (I assume) that it does not have to be implemented. But, abstract methods HAVE to be implemented by concrete classes. What am I missing? Do they mean we can have empty methods?


Solution

  • From https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#clear--

    void clear()

    Removes all of the elements from this collection (optional operation). The collection will be empty after this method returns.

    Throws: UnsupportedOperationException - if the clear operation is not supported by this collection

    It just means that it has to be implemented, but you can state in the docs that you do not support it (for whatever reason), and then you should just throw an UnsupportedOperationException.