Optional method in Java Interface

前端 未结 4 2039
眼角桃花
眼角桃花 2021-01-03 20:46

I have an interface with several method definitions, and I would not like to require some of them.

Is this possible? if so, how can i implement this

4条回答
  •  有刺的猬
    2021-01-03 21:18

    Although I agree with the other answers, one should note that such optional methods exist in the JDK. For example, List.add() is optional. Implementations must throw an UnsupportedOperationException if they don't want to implement this method.

    If you want to be able to know if the optional method is implemented or not, then you could add another method (not optional) :

    /**
     * Returns true if optionalOperation() is supported and implemented, false otherwise
     */
    boolean isOptionalOperationSupported();
    
    /**
     * implements he foobar operation. Optional. If not supported, this method must throw
     * UnsupportedOperationException, and isOptionalOperationSupported() must return false.
     */
    void optionalOperation();
    

提交回复
热议问题