Optional Methods in Java Interface

后端 未结 12 1838
说谎
说谎 2020-11-30 20:53

From my understanding if you implement an interface in java, the methods specified in that interface have to be used by the sub classes implementing the said interface.

12条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 21:42

    All methods have to be implemented for the code to compile, (aside from those with default implementations in Java 8+), but the implementation doesn't have to do anything functionally useful. Specifically, it:

    • May be blank (an empty method.)
    • May just throw an UnsupportedOperationException (or similar)

    The latter approach is often taken in the collection classes - all the methods are still implemented, but some may throw an exception if called at runtime.

提交回复
热议问题