Methods that require return even though Void in the "signature"

5

I'm doing some tests to understand in practice how the class works SwingWorker in% of%, and I noticed that the swing method requires doInBackground return, even starting the variable of the form below:

SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
    @Override
    protected Void doInBackground() throws Exception {

        return null;

    }
};

When declaring null , the first parameter refers exactly to the return of the method mentioned, but even being SwingWorker<Void, Void> , it forces Void to return (if it does not inform the null return, the IDE has a semantic error and does not compile the code). Watch running on IDEONE .

If the signature is null , why does it require return anyway? Is there a difference between protected Void doInBackground() and Void that would justify this behavior?

    
asked by anonymous 21.03.2016 / 16:34

1 answer

7

void is the key word used to indicate that a method returns nothing. In turn Void is a class, so by following the rules, the compiler forces something to be returned.

Void is the "boxing" version of the "primitive type" (1) void . As void indicates no value also Void can not be instantiated .

When a method has Void subscription as its type return, and Void can not be instantiated, the method must return null (which in some way indicates absence of return / value).

The class SwingWorker uses its first parameter type to indicate the type to return by the doInBackground() method, when there is nothing to return it is used Void for the return type.
Generics can only use reference types.

(1) void is not a primitive type

    
21.03.2016 / 17:10