I have a class which defines two overloaded methods
public void handle(Void e)
protected void handle()
Obviously they are different, especially handle(Void e)
is public
.
What's the difference between those two?
How to call the first method? I am using handle(null)
- is this correct?
Void
is a special class usually used only for reflection - its primary use is to represent the return type of a void method. From the javadoc for Void
:
The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.
Because the Void
class can not be instantiated, the only value you can pass to a method with a Void
type parameter, such as handle(Void e)
, is null
.
That's the official version of events, but for those who are interested, despite claims to the contrary in the javadoc of Void
, you can actually instantiate an instance of Void
:
Constructor<Void> c = Void.class.getDeclaredConstructor();
c.setAccessible(true);
Void v = c.newInstance(); // Hello sailor!
That said, I have seen Void
"usefully" used as a generic parameter type when you want to indicate that the type is being "ignored", for example:
Callable<Void> ignoreResult = new Callable<Void> () {
public Void call() throws Exception {
// do something
return null; // only possible value for a Void type
}
}
Callable
's generic parameter is the return type, so when Void
is used like this, it's a clear signal to readers of the code that the returned value is not important, even though the use of the Callable
interface is required, for example if using the Executor
framework.