Wednesday 29 August 2012

Property Syntax - Apex

In Lesson 2: Private Modifiers, you modified the variables to be private, ensuring that they can only be accessed through a method. That's a common pattern when developingApex classes, and there is a shorthand syntax that lets you define a variable and code that should run when the variable is accessed or retrieved.
  1. Add a new property, ecoRating, to the Fridge class by adding the following:
    public Integer ecoRating {
    
       get { return ecoRating; }
    
       set { ecoRating = value; if (ecoRating < 0) ecoRating =0; }
    
    }
    Think of this as creating a variable ecoRating, as well as code that should run when the value is retrieved (the code in the get block) and code that should run when the value is set (the code in the set block). An automatic variable named value is made available to you, so that you know what value is being set. In this case, the properties setter checks for negative ecoRatings, and adjusts them to 0.
  2. Execute the following code to see a negative rating is converted to 0.
    Fridge myFridge = new Fridge('E', 10);
    myFridge.ecoRating = -5;  // calls the setter 
        
    System.debug (myFridge.ecoRating); // calls the getter 
        
    This will output 0.

3 comments: