What is the correct way to return a Void type, when it isn\'t a primitive? Eg. I currently use null as below.
interface B{ E method();
Java 8 has introduced a new class, Optional, that can be used in such cases. To use it, you'd modify your code slightly as follows:
interface B{ Optional method(); }
class A implements B{
public Optional method(){
// do something
return Optional.empty();
}
}
This allows you to ensure that you always get a non-null return value from your method, even when there isn't anything to return. That's especially powerful when used in conjunction with tools that detect when null can or can't be returned, e.g. the Eclipse @NonNull and @Nullable annotations.