Possible Duplicate:
What is the difference between java.lang.Void and void?
I wanted to create a concrete class for SwingWorker
with both final and intermediate result types as void
. I wrote the following code:
class AnswerWorker extends SwingWorker<void, void> {
protected void doInBackGround() {
System.out.println("what is your problem!!");
}
}
This gave me the following error:
Multiple markers at this line-
Syntax error on token "void", Dimensions expected after this token.
Syntax error on token "void", Dimensions expected after this token.
However when i changed the code from void
to Void
(i.e. small v
to capital V
), it worked fine, although I was still forced to return null;
at the end of doInBackground()
method.
Why is this? I know Void
is a class in java.lang
package but the documentation doesn't says much about it (atleast not which i could follow :p)
Thanx in advance!!
class AnswerWorker extends SwingWorker<Void, Void>
Should do the trick.
That is because generics always need objects as parameters. They also can't take primitives. Void is like a Wrapper to get rid of this issue.
Now the cause why you still need to return something:
As the documentation says, Void
is still a class. So you need still to return an object. Since it's uninstantiable, there's only the possibility of returning null
. So Void
isn't fully like the void
keyword. There's still the need to return a reference to an object (null-reference in this case).
There's one important thing: Generics force you to use objects. void
, like primitive types, isn`t an object. That's the pure oop nature of Java ;)
The java.lang.Void
class was originally introduced long before generics as a place to put the constant Void.TYPE
, the Class
object that represents the void
type, and which is returned by java.lang.reflect.Method.getReturnType()
for void
methods (by analogy to Integer.TYPE
, Character.TYPE
, etc. which represent int
, char
, ...).
The Void
class can't be instantiated (therefore the only valid value you can assign to a variable of type Void
is null
) but it has been co-opted since the introduction of generics as a useful token for situations like this where the syntax requires a class name but you don't really want to use one.
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