Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional method in Java Interface

Tags:

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?

I have tried setting an annotation of @Optional but this doesn't seem to work.

Do i have to define the Optional annotation somewhere?

like image 354
james Avatar asked Mar 11 '11 20:03

james


People also ask

CAN interface have optional methods?

The "third statement" says that abstract interface methods must always be implemented and this remains true in Java 8+. However, as in the Java Collections Framework, it is possible to describe some abstract interface methods as "optional" in the contract.

What is optional interface in Java?

Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values.

What is optional type in Java?

The Optional type was introduced in Java 8. It provides a clear and explicit way to convey the message that there may not be a value, without using null. When getting an Optional return type, we're likely to check if the value is missing, leading to fewer NullPointerExceptions in the applications.


1 Answers

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.

like image 76
Erich Douglass Avatar answered Sep 20 '22 07:09

Erich Douglass