Skip to main content
Build the future with Agentforce at TDX in San Francisco or on Salesforce+ on March 5–6. Register now.

Create Classes and Objects

Learning Objectives

After completing this unit, you'll be able to:

  • Describe the relationship between a class and an object.
  • Define a parameter.
  • Explain the differences between return values.

If this is your first stop on the Build Apex Coding Skills trail, you have come too far. Take a step back and go to the Apex Basics for Admins module. If you have already earned the Apex Basics for Admins badge, then you are in the right place.

In Apex Basics for Admins, you learned about Apex syntax, variables, collections, and conditional statements. You also ran some sample code in the Developer Console. In this module we build on those concepts. Let's get started.

What Does Object-Oriented Mean?

If you've read anything about software development or coding, you may have run across the term object-oriented: object-oriented classes, object-oriented concepts, object-oriented programming. What does object-oriented mean?

In relation to programming languages, object-oriented means that the code focuses on describing objects. An object can be anything that has unique characteristics, such as a person, an account, or even a flower. Before you can truly understand what object-oriented means, there are two things that you need to understand: classes and objects.

Follow Along with Trail Together

Want to follow along with an expert as you work through this step? Take a look at this video, part of the Trail Together series on Trailhead Live. You can find a link to the full session in the Resources section.

Classes

A class is a blueprint. Objects are based on classes. A class defines a set of characteristics and behaviors that are common to all objects of that class.

Think about a flower. It has characteristics, such as color and height, and it has behaviors, such as grow and wilt. In an Apex class, the characteristics are called variables and the behaviors are called methods.

A single flower.

Characteristics (Variables)
Behaviors (Methods)
color
Grow
height
Pollinate
maxHeight
Wilt
numberOfPetals

Imagine a garden. Although roses, lilies, and daisies have different colors and heights, they're all flowers and they all have color and height.

A muted color flower representing the class, with three smaller flowers below it representing the instances of the class.

Declaring a Class

This code declares (creates) a class:

public class Flower { //body of class }

Classes are declared using four parts: the access modifier, the keyword "class", the class name, and the class body. The body (inside the curly braces { } ), is where methods and variables of the class are defined.

Access Modifier

An access modifier is a keyword in a class or method declaration. The access modifier determines what other Apex code can see and use the class or method. Although there are other access modifiers, public is the most common. Public classes are available to all other Apex classes within your org.

Methods

Methods are defined within a class. A method describes the behaviors inherited by objects of that class. A class can have one or more methods. The Flower class has three methods (behaviors): grow, pollinate, and wilt.

A method is declared (created) like this:

 public static Integer wilt(Integer numberOfPetals){ //body of method }

Parameters

When creating methods, you don't always know every value needed to run the code. Many times, you write a method that does one task, and then write a second method to do a similar task, and so on. In hindsight you realize that all of your methods do nearly the same thing. They're duplicates with small variations.

If only there were a way to provide varied input to a single method. But wait! We can use parameters! A parameter is a variable that serves as a placeholder, waiting to receive a value. Parameters are declared similarly to a variable, with a data type followed by the parameter name. In the following declaration, the wilt method has a parameter named numberOfPetals. (Although you can use whatever parameter names you like, it's a good practice to use names that describe the value that the parameter holds.) The numberOfPetals parameter expects to receive a value whose data type is integer.

<p>public static void wilt (Integer numberOfPetals){</p><p> //body of method</p><p>}</p>

How do we call (use) the wilt method? In this code sample, the first line calls (uses) the method and passes (sends) the value 4. The value that you pass is called an argument. The argument (4, in this case) is enclosed in parentheses after the method name.

wilt(4);
public static void wilt(Integer numberOfPetals){
    system.debug(numberOfPetals);
}

After a value is passed to a method that includes a parameter, the argument value becomes the value of the parameter. The parameter functions as a variable, so you can manipulate it like any other variable.

Let's look at the Flower class.

public class Flower {
    public static void wilt(Integer numberOfPetals){
        if(numberOfPetals >= 1){
            numberOfPetals--;
        }
    }
}

In lines 2-6 of the Flower class, the wilt method checks the value of numberOfPetals. If that number is greater than or equal to 1, then the wilt method decrements (reduces) the numberOfPetals by one.

Return Types

Imagine you're in a restaurant and you want to know if they have a seasonal dish. You ask the waiter, “Do you have the summer salad?” You expect a particular type of response, not a number or a full sentence, but either “yes” or “no.”

A method declaration must explicitly state its expected return type. In the same way that an argument must match the data type specified by the parameter, a returned variable must match the return type specified by the method declaration. The return type is a specific data type, such as Boolean, String, or Account, or it can be void (nothing), like this:

public static void wilt(Integer numberOfPetals){
    system.debug(numberOfPetals);
}

When the method return type is void, the method does not return a value. To return a value, replace void with a different return type.

For example, here, the wilt method expects a return (response) value that's an integer.

public static Integer wilt (Integer numberOfPetals){ //body of method}

public static Integer wilt(Integer numberOfPetals){
    if(numberOfPetals >= 1){
        numberOfPetals--;
    }
  
    return numberOfPetals;
}

In line 1, the return type Integer (immediately after public static) indicates that the method returns a value that's an integer. Line 6 uses the return statement, followed by the numberOfPetals variable name, to return the resulting numberOfPetals value. When a method returns a variable value, the variable data type must match the return type that the method declared. In this case, the wilt method is expected to return an integer value and the numberOfPetals variable is an integer.

Let's test the wilt, grow, and pollinate methods. First, we finish coding the methods.

Write the Methods

  1. In the Developer Console, click File | New | Apex Class.
  2. Enter Flower for the class name.
  3. Click OK.
  4. In the Flower.apxc class, replace the existing code with this code:
    public class Flower {
        // class variables:
        public String color;
        public Integer height;
        public Integer maxHeight;
        public Integer numberOfPetals;
      
        public static Integer wilt(Integer numberOfPetals){
            if(numberOfPetals >= 1){
                numberOfPetals--;
            }
            return numberOfPetals;
        }
      
        public static void grow(Integer height, Integer maxHeight){
            height = height + 2;
            if(height >= maxHeight){
                pollinate();
            }
        }
      
        public static void pollinate(){
            System.debug('Pollinating...');
        }
    }
  5. Click File | Save.

Now that you have a fully defined class, you're ready to test it. All you need is the class name (Flower), the methods that you want to test (wilt and grow), and each method's required arguments. Because the grow method calls (uses) the pollinate method, you don't need to call the pollinate method directly. The wilt method expects an integer value (for the numberOfPetals parameter) and it will return an integer value. The grow and pollinate methods don't return anything.

Run the Methods

  1. Click Debug | Open Execute Anonymous Window.
  2. In the Enter Apex Code window, paste this code:
    Flower.wilt(4);
    Flower.grow(5, 7);
  3. Select Open log and then click Execute. The Execution Log opens, displaying the result of running your code.
  4. Select Debug Only.

The grow method includes two parameters, height and maxHeight.

Flower.grow(5, 7); passes the arguments 5 (height is 5 inches) and 7 (maximum height is 7 inches) to the grow method. The grow method adds 2 to the height variable (line 9) and then checks the value of the height variable. If the value of the height variable is greater than or equal to the value of the maxHeight variable, the grow method calls the pollinate method.

The pollinate method does not return anything because its return type is void.

What happened?

You should see one entry in the Debug log.

Event: USER_DEBUG. Details: [18]|DEBUG|Pollinating…

What do you expect to happen if you use 2 and 6 for the grow parameters? Try it.

What happens?

Looking at the debug logs it appears to be nothing. What is happening is that setting the height to 2 and the maxHeight to 6 makes the condition in the if statement false, causing the pollinate method not to run.

Objects

Remember that the Flower class is a blueprint for creating flowers. It has color, height, maxHeight, and numberOfPetals variables. These variables are equal to null (no value), but they can have default values.

An object is an instance of a class. In the same way that kids inherit genetic traits, such as eye color and height, from their parents, objects inherit variables and methods from their classes.



color = null;
height = null;
maxHeight = null;
numberOfPetals = null;
Flower Class
Muted shade flower.


grow()

pollinate()

wilt()
Yellow flower.
Red flower.
Pink flower.
color = 'yellow';
color ='red';
color = 'pink';
height = 3;
height = 6;
height = 9;
maxHeight = 6;
maxHeight = 8;
maxHeight = 9;
numberOfPetals = 4;
numberOfPetals = 6;
numberOfPetals = 10;
Flower tulip = new Flower();
tulip.color = 'yellow';
tulip.height = 3;
tulip.maxHeight = 6;
tulip.numberOfPetals = 4;
tulip.grow();

Flower rose = new Flower();
rose.color = 'red';
rose.height = 6;
rose.maxHeight = 8;
rose.numberOfPetals = 6;
rose.grow();

Flower peony = new Flower();
peony.color = 'pink';
peony.height = 9;
peony.maxHeight = 9;
peony.numberOfPetals = 10;
peony.grow();

The tulip object is an instance of the Flower class. Each of the three flower objects is a specific flower based on the Flower class. To create an instance named tulip, based on the Flower class, use this syntax:

Flower tulip = new Flower();

You can use dot notation to call an object's methods. Just add .method(); after the object name. For example:

tulip.grow();

Now you know that objects are instances of classes. Within a class, variables describe the object, and methods define the actions that the object can perform. You've also worked with parameters to receive passed values in a variable, and return types, which send something (or nothing, depending on the data type) back to a method.

Resources

Condividi il tuo feedback su Trailhead dalla Guida di Salesforce.

Conoscere la tua esperienza su Trailhead è importante per noi. Ora puoi accedere al modulo per l'invio di feedback in qualsiasi momento dal sito della Guida di Salesforce.

Scopri di più Continua a condividere il tuo feedback