Wednesday, 29 August 2012

Private Modifiers - Apex

The class, class methods, and member variables were all declared using the public keyword until now. This is an access modifier that ensures other Apex classes also have access to the class, methods, and variables. Sometimes, you might want to hide access for other Apex classes. This is when you declare the class, method, or member variable with the private access modifier.
By declaring the member variables as private, you have control over which member variables can be read or written, and how they’re manipulated by other classes. You can provide public methods to get and set the values of these private variables. These getter and setter methods are called properties and are covered in more detail in Lesson 6: Property Syntax. Declare methods as private when these methods are only to be called within the defining class and are helper methods. Helper methods don’t represent the behavior of the class but are there to serve some utility purposes.
Note
By default, a method or variable is private and is visible only to the Apex code within the defining class. You must explicitly specify a method or variable aspublic in order for it to be available to other classes.
Let’s modify our Fridge class to use private modifiers for the member variables.
  1. Modify the Fridge class and change the modifier of both variables to private:
    private String modelNumber;
    private Integer numberInStock;
  2. Click Quick Save.
  3. Execute the following in the Developer Console:
    Fridge myFridge = new Fridge();
    myFridge.modelNumber = 'MX-EO';
    You'll receive an error warning: Variable is not visible: modelNumber. The variable modelNumber is now only accessible from within the class—a good practice.
  4. To provide access to it, define a new public method that can be called to set its value and another to get its value. Add the following inside the class body of Fridge.
    public void setModelNumber(String theModelNumber) {
        modelNumber = theModelNumber;
    }
    
    public String getModelNumber() {
        return modelNumber;
    }
  5. Click Quick Save.
  6. Execute the following:
    Fridge myFridge = new Fridge();
    myFridge.setModelNumber('MX-EO');
    System.debug(myFridge.getModelNumber());
    This will execute properly. The call to the setModelNumber method passes in a string which sets the modelNumber value of the myFridge instance variable. The call to the getModelNumber method retrieves the model number, which is passed to the System.debug system method for writing it to the debug output.

No comments:

Post a Comment