Optional method in Java Interface Optional method in Java Interface android android

Optional method in Java Interface


There is no @Optional annotation in Java. One thing you can do is to create an interface, and then create an abstract class that provides stub implementations. Your classes can then extend this base class and override the methods they are interested in.


You can have an Abstract class that implements this interface with empty function implementations and then extend from the Abstract class

Having said that, I would question why you need to do this. Maybe you need to split you interface into multiple smaller ones and implement the only ones that you need for a class


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();