9

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

2 Answers 2

19

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
  • 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
    Commented Mar 13, 2017 at 17:41
  • You can drop the assignment altogether from your first example. Declared variables are null until assigned.
    – Adrian Larson
    Commented Mar 14, 2017 at 14:38
1

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .