Wednesday 29 August 2012

Constructors - Apex

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.
  1. Add the following to your Fridge class:
    public Fridge() {
        modelNumber = 'XX-XX';
        numberInStock = 0;
    }
    
    public Fridge(String theModelNumber, Integer theNumberInStock) {
        modelNumber = theModelNumber;
        numberInStock = theNumberInStock;
    }
    The constructor looks like a method, except it has the same name as the class itself, and no return value.
  2. 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());
    This will output 'MX-EO'. You'll often see classes with a variety of constructors that aid object creation.

1 comment:

  1. Thanks for this information; I hope it will use much reader who looking you regularly likes me…
    Regards,
    Salesforce courses in Chennai|Salesforce institutes in Chennai

    ReplyDelete