Apex classes are similar to Java classes. A class is a template or blueprint from which objects are created. An object is an instance of a class. For example, a Fridge class describes the state of a fridge and everything you can do with it. An instance of the Fridge class is a specific refrigerator that can be purchased or sold.
An Apex class can contain variables and methods. Variables are used to specify the state of an object, such as the object's name or type. Since these variables are associated with a class and are members of it, they are referred to as member variables. Methods are used to control behavior, such as purchasing or selling an item.
Methods can also contain local variables that are declared inside the method and used only by the method. Whereas class member variables define the attributes of an object, such as name or height, local variables in methods are used only by the method and don’t describe the class.
Tutorial #4: Creating and Instantiating Classes in Chapter 1 of this workbook shows how to create a new class. Follow the same procedure, and create the following class:
public class Fridge { public String modelNumber; public Integer numberInStock; public void updateStock(Integer justSold) { numberInStock = numberInStock - justSold; } }
You’ve just defined a new class called Fridge. The class has two member variables, modelNumber and numberInStock, and one method, updateStock. Thevoid type indicates that the updateStock method doesn’t return a value.
You can now declare variables of this new class type Fridge, and manipulate them. Execute the following in the Developer Console:
Fridge myFridge = new Fridge(); myFridge.modelNumber = 'MX-O'; myFridge.numberInStock = 100; myFridge.updateStock(20); Fridge myOtherFridge = new Fridge(); myOtherFridge.modelNumber = 'MX-Y'; myOtherFridge.numberInStock = 50; System.debug('myFridge.numberInStock=' + myFridge.numberInStock); System.debug('myOtherFridge.numberInStock=' + myOtherFridge.numberInStock);
This creates a new instance of the Fridge class, called myFridge, which is an object. It sets the values of the variables in the object, and then calls the updateStockmethod, passing in an argument of value 20. When this executes, the updateStock instance method will subtract the argument from the numberInStock value. Next, it creates another instance of the Fridge class and sets its stock number to 50. When it finally outputs the values, it displays 80 and 50.
No comments:
Post a Comment