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?
In C, an empty parameter list means that the number and type of the function arguments are unknown. Example: int f(); // means int f(void) in C++ // int f( unknown ) in C. In C, it makes sense to avoid that undesirable "unknown" meaning. In C++, it's superfluous.
In computer programming, when void is used as a function return type, it indicates that the function does not return a value. When void appears in a pointer declaration, it specifies that the pointer is universal. When used in a function's parameter list, void indicates that the function takes no parameters.
The way that a non-void method is called differs from the way that a void method is called in that the call is made from within other Java statements. Since a non-void method always returns a value, this value has to be stored in a variable, printed, or returned to a Java control structure or another method.
A void function with value parameters are declared by enclosing the list of types for the parameter list in the parentheses. To activate a void function with value parameters, we specify the name of the function and provide the actual arguments enclosed in parentheses.
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.
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