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.
Let’s modify our Fridge class to use private modifiers for the member variables.
- Modify the Fridge class and change the modifier of both variables to private:
private String modelNumber; private Integer numberInStock;
- Click Quick Save.
- Execute the following in the Developer Console:
Fridge myFridge = new Fridge(); myFridge.modelNumber = 'MX-EO';
- 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; }
- Click Quick Save.
- Execute the following:
Fridge myFridge = new Fridge(); myFridge.setModelNumber('MX-EO'); System.debug(myFridge.getModelNumber());
No comments:
Post a Comment