Activity Forums Salesforce® Discussions what are the use cases of Constructor Overloading ?

  • Piyush

    Member
    October 1, 2019 at 2:57 am

    Hi Yogesh,

    It is completely dependent upon your implementation whether or not you want to create more than one constructor in your class but having more than one constructor can ease your life in many instances.

    Here is an example that you use to create multiple Constructor in apex class:-

    public class SampleController {
        private String myInsVar;
        public SampleController() {
            myInsVar = 'Tes';
        }
    
        @AuraEnabled static void lightningControllerM1() {
            // Here, [[code]]czoxODpcIlNhbXBsZUNvbnRyb2xsZXIoKVwiO3tbJiomXX0=[[/code]] is never called
            // We can't access [[code]]czo4OlwibXlJbnNWYXJcIjt7WyYqJl19[[/code]] in static context.
            String myLocalInsVar = 'Tes'; // this is fine.
        }
    
        @AuraEnabled static void anotherLightningControllerM2() {
            myCustomObject q = new MyCustomObject('Tes');
            // myCustomObject() constructor *is* called, because we instantiated it here.
            // We still can't access [[code]]czo4OlwibXlJbnNWYXJcIjt7WyYqJl19[[/code]].
        }
    }

     

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos