In Java < 8, returning "unsafe" objects (objects or null), I was able to specialize return type in subclass:
class A {}
class B extends A {}
interface Sup { A a(); /* returns A instance, or null */ }
interface Sub extends Sup { B a(); }
In Java 8, if I want to make my API "safer", I should return Optional<A>
instead of "raw" A
:
interface Sup { Optional<A> a(); }
interface Sub extends Sup { Optional<B> a(); }
But doesn't compile! Because Optional<B>
is not a subclass of Optional<A>
.
How I'm supposed to resolve this issue?
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.
Optional Class is a container for an object that may contains null . With this Optional class, we can semantically told clients that a function they will use may return a null value that lead into NullPointerException .
Optional is a container object which may or may not contain a non-null value. You must import java. util package to use this class. If a value is present, isPresent() will return true and get() will return the value.
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. It is introduced in Java 8 and is similar to what Optional is in Guava.
You could use wildcards.
interface Sup { Optional<? extends A> a(); }
interface Sub extends Sup { Optional<? extends B> a(); }
I could have made it just Optional<B>
but using Optional<? extends B>
allows another interface to extend Sub
and do the same thing.
Personally, I think this is a bit of a mess, and it would be preferable to just return A
or B
, or null
where necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With