Salesforce coding lessons for the 99%
Finally, Apex tutorials for point-and-click admins! Written by a self-taught Google engineer.
  • Beginner Tutorials
    • Apex
    • Certifications
    • Career Info
    • Technical Architect
    • Visualforce
    • Videos
  • Apex Academy
  • Success Stories
  • About Me
  • Misc
    • Mailbag
    • Challenges
    • Links
    • Login to my Org
Follow @dvdkliuor SUBSCRIBE!

How to create an Apex class

November 4, 2014

Preface – This post is part of the Object Oriented Thinking series.

Enough theoretical talk about what classes are – it’s time to get our hands dirty and code one!

First things first, here’s where you go in your org to create a class:
Setup >> Develop >> Apex Classes >> New

For this tutorial, let’s build our X-wing class!


If you don’t know what an X-Wing is, you have homework to do!

Every class has three components to it: [1] Attributes, [2] Methods, and [3] Constructors.

1. Attributes

Attributes are the variables that describe your class. Your class’s attributes can be any data type, collection, or even class! Think of attributes to be just like custom fields, except they exist on your class instead of a Salesforce object.

// Basic data type attributes
String name; Integer protonTorpedoes; Integer deathStarsDestroyed; Decimal powerRemaining;
// Attributes related to Salesforce objects - like lookups!
User pilot; Account manufacturer;
// Attributes related to other classes - also like lookups!
LaserCannon lasers; HyperdriveEngine engine; DeflectorShield shield; AstromechDroid droid;

Note that the LaserCannon, HyperdriveEngine, and DeflectorShield classes referenced above would have to already exist for this class to save!

2. Methods

Methods are the actions available to objects of your class. You define the logic inside each method, what inputs are required (if any), and what value is returned (if any). Here’s the general template:

public ReturnType MethodName(Input1Type Input1Variable) {
  // Method logic goes here!
}

ReturnType is simply the data type, collection, or class that’s returned when your method is called. For example, if your method took two Integers and added them together, your return type would be Integer. If you don’t want your method to return anything, use void.

MethodName is whatever you want to name your method! Make sure to choose a method name so descriptive that a Wookiee could understand it! Also, don’t forget to use camelCase.

Input1Type is the data type, collection, or class that represents your first accepted input, and Input1Variable is the variable name you’re assigning it to so you can reference it in your method’s logic. You can add more inputs to your method by separating them with commas.

Let’s create a few methods for our class:

// This method has one input and doesn't return anything
public void shootLasers(Integer numberOfShots) {
for (Integer i = 0; i < numberOfShots; i++) { System.debug('PEW!'); } } // Notice how this method references class attributes! public void fireProtonTorpedo() {
if (protonTorpedoes > 0) {
System.debug('Shoop... KABOOM!!!');
protonTorpedoes--; // This decrements the variable by 1 deathStarsDestroyed++; // This increments the variable by 1
} } // This method returns a value!
public Boolean initiateHyperdrive() {
Boolean isSuccess = false; if (powerRemaining > 0.10) { System.debug('Zoom zoom, WEEE!'); powerRemaining = powerRemaining - 0.10; isSuccess = true; }
return isSuccess;
}

3. Constructors

Constructors are the methods that create new instances of your class, aka objects. Just like with methods, you define the logic and what inputs are required (if any). The difference with methods is that you don’t define a return type because constructors always return a new object.

The goal of a constructor is to prepare your new object for use!

// The name of the constructor "method" is always the class name
public XWing(String nickname, User myUser) {
name = nickname; protonTorpedoes = 2; deathStarsDestroyed = 0; powerRemaining = 1.00; pilot = myUser;
}

Constructors are totally optional – Apex automatically creates a default constructor that simply creates a new object with all empty attributes.

Putting it all together…

public class XWing {
  // Attributes usually come first!
String name; Integer protonTorpedoes; Integer deathStarsDestroyed; Decimal powerRemaining;
User pilot; Account manufacturer;
LaserCannon lasers; HyperdriveEngine engine; DeflectorShield shield; AstromechDroid droid;
// Constructor(s) are next public XWing(String nickname, User myUser) {
name = nickname; protonTorpedoes = 2; deathStarsDestroyed = 0; powerRemaining = 1.00; pilot = myUser;
} // Finally comes the methods
public void shootLasers(Integer numberOfShots) {
for (Integer i = 0; i < numberOfShots; i++) { System.debug('PEW!'); } } public void fireProtonTorpedo() {
if (protonTorpedoes > 0) {
System.debug('KABOOM!!!');
protonTorpedoes--; deathStarsDestroyed++;
} }
public Boolean initiateHyperdrive() {
Boolean isSuccess = false; if (powerRemaining > 0.10) { System.debug('Zoom zoom, WEEE!'); powerRemaining = powerRemaining - 0.10; isSuccess = true; }
return isSuccess;
} }

We’re now ready to start creating objects of this class in our code!

Starting to wrap your head around the concept of objects and classes? Don’t worry if it’s still a little fuzzy to you, it takes months of practice for most people to understand these concepts.

We’ll put this class to you in the next post to “force” it in your head!

Next post: How to use objects in your code!

16 Comments
Angie
January 20, 2018 @ 4:08 am

Hi David,

One word for you!!! You are Lord of Salesforce. It’s some what easy to grab things and work hard to become a salesforce architect in google.
But it is very tough or impossible to think about others and make other people better career helping them.
You are one of them my bro….I see lots of salesforce paid courses. This sfdc99.com is free of cost and the quality of experience you shared is no where available trust me.

Why I said ”Lord” is because you are sharing your knowledge unconditionally and in non profit way and trust me you are the person who will be the most successful man on this earth. My blessings and love.

Lots of Kudos…

Angie

Reply
    David Liu
    January 22, 2018 @ 9:14 pm

    Thank you Angie =) =) =) =) =)

    Reply
    Sirisha
    February 22, 2019 @ 10:07 am

    I second that opinion

    Reply
kuchan vinod
November 7, 2014 @ 6:10 am

Hey devid what is the difference between Sales Cloud and Service Cloud?
what is an API?how it’s useful in salesforce?

Reply
    David Liu
    November 8, 2014 @ 9:41 am

    Sales Cloud = for sales people. Basically revolves around Opportnities

    Service Cloud = for support reps. Basically revolves around Cases.

    API lets external systems connect into Salesforce.

    Reply
      kuchan vinod
      November 8, 2014 @ 10:27 pm

      Thank you david can you explain details about API’s im unable to understand…

      Reply
        David Liu
        November 9, 2014 @ 8:58 pm

        Go Wikipedia!!
        http://en.wikipedia.org/wiki/Application_programming_interface

        I’ll have a tutorial on APIs this year!

        Reply
          Angie
          January 20, 2018 @ 4:11 am

          David, I need basic knowledge on API for salesforce. Kindly share the link for your videos for the same.

          Reply
            David Liu
            January 22, 2018 @ 9:15 pm

            Don’t know of any free ones off the top of my head – hope others can share this!

            Reply
    Chuck
    September 22, 2018 @ 8:59 pm

    Hey Kuchan, check out https://www.programmableweb.com/api-university for a bit more info.

    Reply
John
November 5, 2014 @ 4:47 am

When I save this class I get an error

Error Error: Compile Error: Invalid type: LaserCannon at line 11 column 3

What is wrong with my code?

Reply
    David Liu
    November 5, 2014 @ 8:12 am

    Nothing wrong with your code – we just don’t have any classes that represent LaserCannon, Hyperdrive, or DeflectorShield yet!

    Try changing them to Strings temporarily =)

    David

    Reply
      John
      November 5, 2014 @ 9:10 am

      I just created blank classes for now. Thanks!

      Reply
        David Liu
        November 5, 2014 @ 6:21 pm

        Even better =)

        Reply
tan
November 5, 2014 @ 2:56 am

Input1Type is local to that class right? I think we can declare “Input1Type” inside the class.

public ReturnType MethodName() {

Input1Type Input1Variable; // can we declare this way?
// Method logic goes here!
}

Is there any difference/advantages in both the declarations?

Reply
    David Liu
    November 5, 2014 @ 6:29 pm

    Inputs and variables should be viewed differently, here’s an example!


    public Integer addNumbers(Integer x, Integer y) {
    variable sum = x + y;
    return sum;
    }

    Then we’d call the formula using different inputs:


    addNumbers(5, 4);
    addNumbers(10, 20);

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *


*

*

Theme: Simple Style by Fimply