Apex provides a default constructor for each class you create. For example, you were able to create an instance of the Fridge class by calling new Fridge(), even though you didn’t define the Fridge constructor yourself. However, the Fridge instance in this case has all its member variables set to null because all uninitialized variables inApex are null. Sometimes you might want to provide specific initial values, for example, number in stock should be 0 and the model number should be a generic number. This is when you’ll want to write your own constructor. Also, it’s often useful to have a constructor that takes parameters so you can initialize the member variables from the passed in argument values.
Try adding two constructors, one without parameters and one with parameters.
- Add the following to your Fridge class:
public Fridge() { modelNumber = 'XX-XX'; numberInStock = 0; } public Fridge(String theModelNumber, Integer theNumberInStock) { modelNumber = theModelNumber; numberInStock = theNumberInStock; }
- You can now create an instance and set the default values all at once using the second constructor you’ve added. Execute the following:
Fridge myFridge = new Fridge('MX-EO', 100); System.debug (myFridge.getModelNumber());
Thanks for this information; I hope it will use much reader who looking you regularly likes me…
ReplyDeleteRegards,
Salesforce courses in Chennai|Salesforce institutes in Chennai