2

Possible Duplicate:
Method Overloading for NULL parameter

Quick question about "best practices" when coding in Java. I have a class that can be constructed with two different types of objects (a HashMap or a separate class that I call a SearchTerm). I usually have pretty good handlers in the case where the client gives a null argument through the constructor, but if this does happen, the VM collapses and says the argument was ambiguous. (It makes sense, since the null argument could have been referring to either object.)

How are these situations usually dealt with? Is it bad form to allow separate objects as arguments?

Community
  • 1
  • 1
Sal
  • 3,179
  • 7
  • 31
  • 41
  • 3
    That's a compiler error. What's the problem? – SLaks Jan 20 '12 at 02:12
  • The VM should handle which constructor to call based on the argument type. – Will Jan 20 '12 at 02:19
  • 1
    @WilliamVanRensselaer - but it doesn't. Sal, can you use a factory to construct these objects, and have the factory reject the case where the argument is null? Or if the null case is valid, have a third constructor with one argument fewer that the factory uses. – Dawood ibn Kareem Jan 20 '12 at 02:38
  • This has already been dealt with before: http://stackoverflow.com/questions/5229809/method-overloading-for-null-parameter – eternaln00b Jan 20 '12 at 03:41
  • @DavidWallace - That's what I was looking for! I wanted a good strategy to deal with this situation, and a factory seems to take care of it. Thanks for the link Sid. – Sal Jan 20 '12 at 03:52

1 Answers1

4

Unless I'm misunderstanding something, this ambiguity error should only occur if you try to call the constructor with null as the argument. If you want to work around this, you can cast the argument to the class you want to use, like so:

new YourClass((SearchTerm) null);

That way the compiler knows that even though the argument is null, it's supposed to treat it like a null instance of SearchTerm.

If you have an instance of SearchTerm that happens to be null, there shouldn't be a problem:

SearchTerm searchTerm = null;
new YourClass(searchTerm);

should work without ambiguity errors because the compiler knows the what type the instance is, even though it's null.

Amos M. Carpenter
  • 4,848
  • 4
  • 42
  • 72