I know that all primitive types are objects and can be null in Apex

But is there a way to handle the null value when doing polymorphism ?

public class myClass{
    public myClass(String name){
        // handle input

    public myClass(Integer num){
        // handle input

new myClass(null);

I am getting the error below when trying to instantiate my class with a null value

Error on SFDevConsole


The compiler cannot figure out which method to call here in the anonymous window because you are calling with 'null' explicitly vs having a variable type which it can use to figure out what you want. So, for example this code would work just fine:

String test = null;
new myClass(test);

Or, you could do:

new myClass((String)null);

In both cases we are providing the compiler with the information it needs to figure out which method to call.

  • 2
    +1, but it's not not necessary to assign null to a variable when declaring it, as the default value is null. This just wastes CPU time. Welcome to SFSE! – sfdcfox Mar 13 '17 at 17:41
  • You can drop the assignment altogether from your first example. Declared variables are null until assigned. – Adrian Larson Mar 14 '17 at 14:38

Thank you @Matt for this answer

For me I handled that case like this, because I needed to be able to call myClass with an untyped null

public class myClass{
    public myClass(Object obj){
        if(obj == null){
            // handle input null
        }else if(obj instanceof String){
            // handle input String
        }else if (obj instanceof Integer){
            // handle input Integer
        }else {
            throw new myClassParamException('Error myClass handles only String or integer type');


public class myClassParamException extends Exception {}

new myClass(null);  // No error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.