returning a Void object

Robert picture Robert · Mar 9, 2010 · Viewed 104.4k times · Source

What is the correct way to return a Void type, when it isn't a primitive? Eg. I currently use null as below.

interface B<E>{ E method(); }

class A implements B<Void>{

    public Void method(){
        // do something
        return null;
    }
}

Answer

Bozho picture Bozho · Mar 9, 2010

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

So any of the following would suffice:

  • parameterizing with Object and returning new Object() or null
  • parameterizing with Void and returning null
  • parameterizing with a NullObject of yours

You can't make this method void, and anything else returns something. Since that something is ignored, you can return anything.