Methods that require return even having Void in "signature"

Asked

Viewed 186 times

5

I am doing some tests to understand in practice the functioning of the classSwingWorker in the swing, and I noticed that the method doInBackground demands a return null, even starting the form variable below:

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

        return null;

    }
};

In declaring SwingWorker<Void, Void>, the first parameter refers precisely the return of the method cited, but even if it is Void, he forces to return null(If you do not provide the null return, the IDE displays a semantic error and does not compile the code). See running on IDEONE.

If the signature is protected Void doInBackground(), Why does it require feedback anyway? There is some difference between Void and void to justify this behaviour?

  • "it forces to return null" this comes from the compiler or the IDE?

  • @rray the IDE accuses a "Missing Return statement" semantic error, and neither compiles.

1 answer

7


void is the keyword used to indicate that a method does not return anything.
In turn Void is a class, so, following the rules, the compiler forces something to be returned.

Void is the version "Boxing" of the "primitive type"(1) void. Like void indicates no value either Void cannot be instantiated.

When a method has in its signature Void as a type of return Void be instantiated, the method has to return null(which somehow indicates no return/value).

The class Swingworker uses its first type of parameter to indicate the type to be returned by the method doInBackground(), when there is nothing to return is used Void for the type of return.
Generics may only use reference types.

(1) void is not one primitive type

  • So in the case of Swingworker, as who defines the type of return is who is programming, he forces to use Void so that the method always has return, no matter what type we pass?

  • What forces the return is the signature of the method: protected abstract T doInBackground() it indicates that you must return T which is the type indicated in the first parameter of SwingWorker<T,V>.

  • 3

    How you are required to specify the type of parameters when instantiating Swingworker, if there is nothing to return from the method doInBackground() use the type Void.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.